all groups > sql server mseq > may 2007 >
You're in the

sql server mseq

group:

How to "avoid" a GROUP BY - HAVING


How to "avoid" a GROUP BY - HAVING LUIS
5/29/2007 5:19:00 PM
sql server mseq:
I have four tables,
1. First has Items,
2. Second has Features,
3. Third defines the ItemsFeatures
4. And temporary that sets which Items have to SELECT according Features
For this statment we do not need table(2),

IF (SELECT COUNT(*) FROM tblTemporary) = 0

SELECT A.ItemID, B.ItemDescrip FROM tblItems A ORDER BY 1

ELSE

SELECT A.ItemID, B.ItemDescrip
FROM tblItems A LEFT OUTER JOIN tblItemsFeatures B ON A.ItemID = B.ItemID
LEFT OUTER JOIN tblTemporary C ON B.FeatureID = C.FeatureID
GROUP BY A.ItemID, B.ItemDescrip
HAVING COUNT(B.FeatureID) = (SELECT COUNT(*) FROM tblTemporary)
ORDER BY 1

If I want all Items, first SELECT is used, if I make a Features Selection,
second SELECT is executed.
QUESTION : If there a way to use ONLY ONE SELECT to do this?

Beforehand, thank you very much


--
Luis Garcia
Re: How to "avoid" a GROUP BY - HAVING Hugo Kornelis
5/30/2007 10:12:15 PM
[quoted text, click to view]

Hi LUIS,

The query below should combine these two select statements, though it
does not avoud the GROUP BY and the HAVING (I don't think you can get
the desired results without them).

SELECT A.ItemID, B.ItemDescrip
FROM tblItems A LEFT OUTER JOIN tblItemsFeatures B ON A.ItemID =
B.ItemID
LEFT OUTER JOIN tblTemporary C ON B.FeatureID =
C.FeatureID
GROUP BY A.ItemID, B.ItemDescrip
HAVING COUNT(B.FeatureID) = COALESCE(NULLIF((SELECT COUNT(*) FROM
tblTemporary),0),COUNT(B.FeatureID))
ORDER BY 1

(Untested - see www.aspfaq.com/5006 if you prefer a tested reply)

BTW, do you really think that the joins need to be OUTER joins? I doubt
it, but without more information than you gave I can't be completely
sure. You might want to check if you can use INNER joins instead, since
they are often a tad faster.

--
Hugo Kornelis, SQL Server MVP
AddThis Social Bookmark Button