patternsqlMinor
Single query to return counts over different IDs in a single record
Viewed 0 times
returnqueryidsoverdifferentrecordsinglecounts
Problem
select count(title_id)as algodata from titles where pub_id =1389
select count(title_id)as binnet from titles where pub_id =0877
select count(title_id)as newmoon from titles where pub_id =0736The database used is
pubs in SQL Server.Can I use a single query to show the count of records for each publisher (here there are 3 publishers) in a single record?
Solution
Similar to @ypercubes but to get one row without 3 separate queries
Also, decide if your values are numbers or strings and be consistent to avoid datatype conversions
select
count(CASE WHEN pub_id = '1389' THEN title_id END) as algodata,
count(CASE WHEN pub_id = '0877' THEN title_id END) as binnet,
count(CASE WHEN pub_id = '0736' THEN title_id END) as newmoon
from titles
where pub_id IN ('1389', '0877', '0736')Also, decide if your values are numbers or strings and be consistent to avoid datatype conversions
Code Snippets
select
count(CASE WHEN pub_id = '1389' THEN title_id END) as algodata,
count(CASE WHEN pub_id = '0877' THEN title_id END) as binnet,
count(CASE WHEN pub_id = '0736' THEN title_id END) as newmoon
from titles
where pub_id IN ('1389', '0877', '0736')Context
StackExchange Database Administrators Q#22148, answer score: 9
Revisions (0)
No revisions yet.