我在SQL Server中的兩個表2008 R2:如何編寫一個帶數和組由共同的領域SQL兩個表
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
你可以看到問題所在。
首先,我想要在'形狀'下而不是NULL'橢圓形'。使用FULL JOIN爲我提供了兩個表中的所有變體,但沒有顯示它們...
其次,我希望Picked和Finished顯示0而不是NULL,表示缺少的變量。
第三,如果可能,我希望SQL更高效。
你如何解決這些問題?
謝謝!
您可能必須進行聯合。 Schema and values pls .. – nawfal