Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Looking for help to simplify a SQL query

Status
Not open for further replies.

pennstump

Technical User
Nov 6, 2003
12
US
Hi all. I would appreciate it if you could take a moment to review my SQL code, which is now in the form of 3 statements with temporary views, and point me in the direction of simplifying it into 1 statement.


CREATE TEMP VIEW voidedCounts AS (SELECT pibatch AS batch,count(*) AS counted FROM tags WHERE pibatch IN (SELECT DISTINCT bcbatch FROM batch ORDER BY bcbatch) AND pivoid=true GROUP BY pibatch ORDER BY pibatch);

CREATE TEMP VIEW totalBatchCounts AS (SELECT pibatch AS batch,count(*) AS counted FROM tags WHERE pibatch IN (SELECT DISTINCT bcbatch FROM batch ORDER BY bcbatch) GROUP BY pibatch ORDER BY pibatch);

SELECT voidedBatchCounts.batch FROM voidedBatchCounts INNER JOIN totalBatchCounts ON voidedBatchCounts.batch=totalBatchCounts.batch WHERE (voidedBatchCounts.counted/totalBatchCounts.counted)=1;


Here are the simplified database tables:


CREATE TABLE "batch"
(
"bcbatch" serial,
PRIMARY KEY ("bcbatch")
);

CREATE TABLE "tags"
(
"pitag" serial,
"pibatch" int,
"pivoid" bool,
PRIMARY KEY ("pitag")
);


Essentially, multiple tags exist in a batch and I'm looking to see which batch IDs (pibatch is a foreign key to bcbatch) have 100% of their tags' void flags set to TRUE.

Can someone see a way to get this into 1 statement? Thanks!
 
SELECT pibatch
FROM tags
GROUP BY pibatch
HAVING COUNT(*)=SUM(CASE WHEN pivoid THEN 1 ELSE 0 END)

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
It does, thank you. Is the CASE statement universal to all/most DBMSs?
 
Except of course for Access where the IIF construct takes that role (... most inelegantly, I might add.)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top