CREATE TABLE PCIDTest (PCID varchar(10), Qty int, BarCode varchar(20), Available bit) insert into pcidtest values ('3U60LB987', 4, 'cIV3V00TCJ42', 1), ('3U60LB987' , 4, 'cIV3V00TCJ43' , 1), ('3U60LB987' , 4, 'cIV3V00TCJ44' , 1), ('3U60LB987' , 4, 'cIV3V00TCJ45' , 1), ('3U60LB987' , 4, 'cIV3V00TCJ46' , 0), ('3V60K0MGW' , 1, 'cIV3V60K1GA0' , 1)
PCID MaxQty NumAvail NumNotAvail 3U60LB987 4 4 1 3V60K0MGW 1 1 0So basically, a conditional aggregation/count based on the Available bit flag
select PCID, max(qty) AS Qty, sum( case when Available = 1 then 1 else 0 end) as NO_AVAIL, sum( case when Available = 0 then 1 else 0 end) as NO_NOTAVAIL from PCIDTEST GROUP BY PCIdJust to offer a 2nd approach (one with a more complicated execution plan, though performance appears to be the same on a table with a million test rows), I was curious about doing this with a few subqueries and a condition.
SELECT PCID, MAX(Qty) as MaxQty, (SELECT COUNT(*) FROM PCIDTest Inside WHERE Inside.PCID = Outside.PCID AND Inside.Available = 1) AS NumAvail, (SELECT COUNT(*) FROM PCIDTest Inside WHERE Inside.PCID = Outside.PCID AND Inside.Available = 0) AS NumNotAvail FROM PCIDTest Outside GROUP BY PCIDI created an index on the PCID column and on PCID plus the Available flag, and the execution times in milliseconds are usually about the same.