473,395 Members | 1,411 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

SQL Join Problem

I'm having a bit of a SQL problem and I can't figure it out. I have a
working solution, but it could be better.

I've got two tables, tblInspections and tblViolations. Each inspection
record has an associated establishment id. Each inspection record can have
multiple violation records associated with it. Each violation can be either
of type 1 (critical) or 0 (noncritical).

What I want is to get a list of inspections by establishmentid with a column
for the count of noncritical violations, and a count of critical violations.

EG.

Date NonCriticalViolations CriticalViolations

5/30/2003 6 2

Here is my SQL and what it returns.

----------------------------------------------------------------------------
----------------------------------------------------------------

select

tblInspections.ReceivedByDate,

tblViolations.Type,

count(tblViolations.Type) as ViolationCount

from

tblinspections

join tblViolations on tblInspections.ID = tblviolations.InspID

where tblInspections.iestabid = 100

group by

tblViolations.Type,

tblInspections.ReceivedByDate

----------------------------------------------------------------------------
----------------------------------------------------------------

and it returns:
+++++++++++++++++++++++

Date: Type Count

2003-05-20 0 2

2003-05-20 1 2

+++++++++++++++++++++++

I can work with this (because it is correct), but would prefer it all on one
record.

Here's what I've tried:

----------------------------------------------------------------------------
----------------------------------------------------------------

select

tblInspections.ReceivedByDate,

count(NCritVios.Type) as NCritViolationCount,

count(CritVios.Type) as CritViolationCount

from

tblInspections

join tblViolations as NCritVios on NCritVios.Type = 0 and
tblInspections.ID = NCritVios.InspID

join tblViolations as CritVios on CritVios.Type = 1 and
tblInspections.ID = CritVios.InspID

where

tblInspections.iestabid = 100

group by

tblInspections.ReceivedByDate, NCritVios.Type

----------------------------------------------------------------------------
----------------------------------------------------------------

and it retuns:

+++++++++++++++++++++++

Date: NCrit Crit

2003-05-20 4 4

+++++++++++++++++++++++

which is not correct.

Note that without the second count in the select and without the second
join, it works (counts ncrits correctly). It's that second join.

Any ideas?

Thanks.

Thom
Jul 20 '05 #1
4 2145
Here's the solution I found, if anybody cares.

select
tblInspections.ReceivedByDate,
(select count(tblViolations.id) from tblViolations
where tblViolations.Type = 0 and tblViolations.inspID =
tblInspections.ID) as NonCriticals,
(select count(tblViolations.id) from tblViolations
where tblViolations.type = 1 and tblViolations.inspID =
tblInspections.ID) as Criticals
from tblInspections


"Thomas Brown" <th**@semo.net> wrote in message
news:10*************@corp.supernews.com...
I'm having a bit of a SQL problem and I can't figure it out. I have a
working solution, but it could be better.

I've got two tables, tblInspections and tblViolations. Each inspection
record has an associated establishment id. Each inspection record can have multiple violation records associated with it. Each violation can be either of type 1 (critical) or 0 (noncritical).

What I want is to get a list of inspections by establishmentid with a column for the count of noncritical violations, and a count of critical violations.
EG.

Date NonCriticalViolations CriticalViolations

5/30/2003 6 2

Here is my SQL and what it returns.

-------------------------------------------------------------------------- -- ----------------------------------------------------------------

select

tblInspections.ReceivedByDate,

tblViolations.Type,

count(tblViolations.Type) as ViolationCount

from

tblinspections

join tblViolations on tblInspections.ID = tblviolations.InspID

where tblInspections.iestabid = 100

group by

tblViolations.Type,

tblInspections.ReceivedByDate

-------------------------------------------------------------------------- -- ----------------------------------------------------------------

and it returns:
+++++++++++++++++++++++

Date: Type Count

2003-05-20 0 2

2003-05-20 1 2

+++++++++++++++++++++++

I can work with this (because it is correct), but would prefer it all on one record.

Here's what I've tried:

-------------------------------------------------------------------------- -- ----------------------------------------------------------------

select

tblInspections.ReceivedByDate,

count(NCritVios.Type) as NCritViolationCount,

count(CritVios.Type) as CritViolationCount

from

tblInspections

join tblViolations as NCritVios on NCritVios.Type = 0 and
tblInspections.ID = NCritVios.InspID

join tblViolations as CritVios on CritVios.Type = 1 and
tblInspections.ID = CritVios.InspID

where

tblInspections.iestabid = 100

group by

tblInspections.ReceivedByDate, NCritVios.Type

-------------------------------------------------------------------------- -- ----------------------------------------------------------------

and it retuns:

+++++++++++++++++++++++

Date: NCrit Crit

2003-05-20 4 4

+++++++++++++++++++++++

which is not correct.

Note that without the second count in the select and without the second
join, it works (counts ncrits correctly). It's that second join.

Any ideas?

Thanks.

Thom

Jul 20 '05 #2
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are. Does your boss often ask you to program without this
information?

Plese read ISO-11179 so you'll know why not ot put that silly "tbl-"
prefix on table names. That is, unless this database deals furniture
inspections, which is what you are saying in ISO terms.
I've got two tables, inspections and violations. Each inspection record [sic] has an associated establishment id. Each inspection record
[sic] can have multiple violation records [sic] associated with it. Each
violation can be either of type 1 (critical) OR 0 (non-critical). <<

You have all the classic newbie design flaws and misconceptions. Rows
are not records; fields are not columns; tables are not files. A data
element does not change its name because of the table it appears in.
There is no "Magical, Global, one-size-fits-all id" -- to be is to be
something in particular and to be a general, vague nothing in particular
is to be nothing. DATE is a reserved word in Standard SQL as well as
too vague to a data element name. And I am almost willing to bet that
you are using IDENTITY as the key to tables, completing the list of
Newbie design errors.

Of course your inspection tickets do have a check digit or other
built-in validation. You did include DRI and DRI actions (a major
reason talbes are not files). To my mind, a violation is the situation
that appears on a citation; a citation is issued for a violation found
in an inspection at a particular establishment. Is this what you meant
to post?

CREATE TABLE Inspections
(insp_id INTEGER NOT NULL PRIMARY KEY
CHECK (<< validation rule >>),
estab_id INTEGER NOT NULL
REFERENCES Establishments (estab_id),
receivedbydate DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
..);

CREATE TABLE Citations
(insp_id INTEGER NOT NULL
REFERENCES Inspections(insp_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
violation_code INTEGER NOT NULL
REFERENCES Violations (violation_code)
ON DELETE CASCADE
ON UPDATE CASCADE,
violation_type INTEGER NOT NULL
CHECK (violation_type IN (0, 1)),
..);
What I want is to get a list of inspections by establishment_id with

a column for the count of non-critical violations, and a count of
critical violations. <<

You ask for it by establishment, then show it by date! Kinda like the
joke about "line up alphabetically by height!" -- I'll do the written
version of the spec:

SELECT I1.estab_id,
SUM (CASE WHEN C1.violation_type = 1 THEN 1 ELSE 0 END)
AS critical,
SUM (CASE WHEN C1.violation_type = 0 THEN 1 ELSE 0 END)
AS non_critical
FROM Citations AS C1, Inspections AS I1
WHERE C1.insp_id = I1.insp_id
GROUP BY I1.I1.estab_id;

I am not sure if a violation type ought to be in the violations, or if
the same violation can be deemed to be critical/non-critical on each
citation (example: violation 1010 = "uncovered food container"; critical
when food is 3 day old oysters, non-critical when food is cheese). I
took the latter assumption and let each inspecotr make a judgement call.

--CELKO--
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #3
[posted and mailed, please reply in news]

Thomas Brown (th**@semo.net) writes:
select tblInspections.ReceivedByDate,
tblViolations.Type,
count(tblViolations.Type) as ViolationCount
from tblinspections
join tblViolations on tblInspections.ID = tblviolations.InspID
where tblInspections.iestabid = 100
group by tblViolations.Type,
tblInspections.ReceivedByDate

and it returns:

Date: Type Count
2003-05-20 0 2
2003-05-20 1 2

I can work with this (because it is correct), but would prefer it all on
one record.


The same solution as Joe Celko, just not buried among his standard
diatribe:

select i.ReceivedByDate,
SUM (CASE i.Type WHEN 0 THEN 1 ELSE 0 END) AS NonCritCnt
SUM (CASE i.Type WHEN 1 THEN 1 ELSE 0 END) AS CritCnt
from tblinspections i
join tblViolations v on i.ID = v.InspID
where i.iestabid = 100
group by i.ReceivedByDate
--
Erland Sommarskog, SQL Server MVP, so****@algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #4
>> The same solution as Joe Celko, just not buried among his standard
diatribe: <<

That was a hand-made, custom diatribe!

--CELKO--
===========================
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are.

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: B. Fongo | last post by:
I learned MySQL last year without putting it into action; that is why I face trouble in formulating my queries. Were it a test, then you would have passed it, because your queries did help me...
2
by: Bruce Duncan | last post by:
I'm a bit new to MySQL (know MS SQL well...and that may be the problem...getting the syntax confused) and I'm having a join problem...can anyone offer some help? Here's my problem: I have table1...
7
by: Greg | last post by:
I'm a quantitative securities analyst working with Compustat data (company fiscal reports and pricing feeds). My coworker came across a problem that we fixed, but I'd like to understand 'why' it...
4
by: Anthony Robinson | last post by:
I was actually just wondering if someone could possibly take a look and tell me what I may be doing wrong in this query? I keep getting ambiguous column errors and have no idea why...? Thanks in...
12
by: Phil Powell | last post by:
<cfquery name="getAll" datasource="#request.dsn#"> SELECT U.userID, U.fname, U.lname, U.phone, U.lastLoggedIn, U.choiceId, U.experience, T.label AS teamLabel, R.label AS roleLabel FROM User U...
5
by: jason.evans | last post by:
Hi there. I am having an intrigueing problem. I have a query which left joins another query to itself twice. The original query is derived from a linked table in SQLServer 2000. When I run...
33
by: Steve | last post by:
One of our clients recently upgraded their Office version to 2003. When they tried to run our program (written in Access 2000), they ended up with the wrong data. My coworker and I have tested this...
52
by: MP | last post by:
Hi trying to begin to learn database using vb6, ado/adox, mdb format, sql (not using access...just mdb format via ado) i need to group the values of multiple fields - get their possible...
18
by: Dave | last post by:
Guys I am really stuck on this one. Any help or suggestions would be appreciated. We have a large table which seemed to just hit some kind of threshold. They query is somewhat responsive when...
3
by: Anila | last post by:
Hi Friends, My problem with Inner join is ... first i joined two tables and i got the result. after that iam trying to join one more table its giving syn tax error in JOIN condition. ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.