遇到分组求和的问题
建表脚本
select shelfid,count(distinct goodsid) 'goodsidcount'
from testtb
group by shelfid
/*
shelfid goodsidcount
-------------------------------------------------- ------------
1 3
2 3
(2 row(s) affected)
*/
select shelfid,COUNT(goodsidcount )goodsidcount
FROM (
SELECT shelfid,COUNT(goodsid) goodsidcount
FROM testtb
GROUP BY shelfid,goodsid
HAVING COUNT(goodsid)>1)a
GROUP BY shelfid
SELECT a.shelfid ,
ISNULL(COUNT(goodsidcount), 0) goodsidcount
FROM ( SELECT DISTINCT
shelfid
FROM testtb
) a
LEFT JOIN ( SELECT shelfid ,
COUNT(goodsid) goodsidcount
FROM testtb
GROUP BY shelfid ,
goodsid
HAVING COUNT(goodsid) > 1
) b ON a.shelfid = b.shelfid
GROUP BY a.shelfid