Reputation: 609
I have this simple query:
SELECT
a.new_funderidname as Funder,
COUNT(a.new_funderidname) as Units
FROM new_dealsheet a
LEFT JOIN salesorder B ON a.new_dsheetid = B.salesorderid
WHERE a.New_PassedToAdmin = 1
GROUP BY a.new_funderidname
ORDER BY Units desc
That's fine, but my B table contains another field called maint, I need to also get the counts for those two possible values, something like
SELECT
a.new_funderidname as Funder,
COUNT(a.new_funderidname) as Units,
COUNT(a.new_funderidname) **WHERE b.maint=1 as UnitsMaint**,
COUNT(a.new_funderidname) **WHERE b.maint=0 as UnitsNotMaint**
FROM new_dealsheet a
LEFT JOIN salesorder B ON a.new_dsheetid = B.salesorderid
WHERE a.New_PassedToAdmin = 1
GROUP BY a.new_funderidname
ORDER BY Units desc
Can I do that within a single query?
Thanks
Upvotes: 0
Views: 70
Reputation: 28890
Use CASE
SELECT
a.new_funderidname as Funder,
COUNT(a.new_funderidname) as Units,
sum(case when b.maint=1 then 1 else 0 end ) as UnitsMaint,
sum(case when b.maint=0 then 1 else 0 end ) as UnitsNotMaint,
FROM new_dealsheet a
LEFT JOIN salesorder B ON a.new_dsheetid = B.salesorderid
WHERE a.New_PassedToAdmin = 1
GROUP BY a.new_funderidname
ORDER BY Units desc
Upvotes: 4
Reputation: 915
You could use PIVOT function.
select Funder,
UNITSMAINT+UNITSNOTMAINT as UNITS,
UNITSMAINT,
UNITSNOTMAINT
from
(
SELECT
a.new_funderidname as Funder,b.Maint
FROM new_dealsheet a
LEFT JOIN salesorder B ON a.new_dsheetid = B.salesorderid
WHERE a.New_PassedToAdmin = 1
)
PIVOT
(
count(b.Maint)
For(1 as UNITSMAINT,0 as UNITSNOTMAINT)
);
Refer Pivot function
Upvotes: 0
Reputation: 12544
If maint is always 0 or 1 you could sum them with Sum(b.mainnt)
and Sum(1-b.mainnt)
SELECT
a.new_funderidname as Funder,
COUNT(a.new_funderidname) as Units,
Sum(b.mainnt) as UnitsMaint,
Sum(1 - b.mainnt) as UnitsNotMaint
FROM new_dealsheet a
LEFT JOIN salesorder B ON a.new_dsheetid = B.salesorderid
WHERE a.New_PassedToAdmin = 1
GROUP BY a.new_funderidname
ORDER BY Units desc
You might need to do a cast inside Sum
if b.mainnt is a bit
type: e.g. SUM(cast(b.mainnt as int))
and SUM(1 - cast(b.mainnt as int))
Upvotes: 1