我在 SQL Server 2008 R2 中有两个表:
Store: Record:
-------------- ------------------------
Shape ID PickedShape Finished
Circle 1 Circle Y
Circle 2 Circle N
Circle 3 Square N
Square 1 Square N
Square 2 Oval Y
Triangle 1 Oval Y
我想编写一个 SQL 查询来输出两个表中所有可能的形状及其计数。我可以用愚蠢的方式写它,比如
select
'Circle', (select count(1) from Store where Shape = 'Circle'),
(select count(1) from Record where PickedShape = 'Circle'),
(select count(1) from Record where Finished = 'Y' and PickedShape = 'Circle')
UNION
select
'Square', (select count(1) from Store where Shape = 'Square'),
(select count(1) from Record where PickedShape = 'Square'),
(select count(1) from Record where Finished = 'Y' and PickedShape = 'Square')
UNION...
继续,但这只是愚蠢而且效率不高。
我认为更聪明的方法是使用 group by。由于有些人可能不喜欢用勺子喂别人,所以这是我尝试过的
SELECT
Shape, COUNT(Shape) AS Available, Picked, Finished
FROM
Store
FULL JOIN
(SELECT PickedShape, COUNT(1) As Picked, SUM(CASE WHEN Finished='Y' THEN 1 ELSE 0 END) AS Finished
FROM Record
GROUP BY PickedShape) t2 ON Store.Shape = t2.PickedShape
GROUP BY
Shape, Picked, Finished
输出是
Shape Available Picked Finished
NULL 0 2 2
Circle 3 2 1
Square 2 2 0
Triangle 1 NULL NULL
你可以看到问题出在哪里。
首先,我想在 Shape 下使用“Oval”而不是 NULL。使用 FULL JOIN 为我提供了两个表中的所有变体,但没有显示它们......
其次,我希望 Picked and Finished 为缺失的显示 0 而不是 NULL。
第三,如果可能的话,我希望 SQL 更高效。
你如何解决这些问题?
谢谢!