2009-08-08 109 views
1

我有一個MEMBERS表具有以下相關欄目:如何從多個SQL選擇器加入彙總結果?

Name 
JoinDate 
Level --1=Gold,2=Silver,3=Bronze** 

我想創建一個查詢返回一個成員總結,列出誰參加了由年份和會員級別的總數。基本上,我的結果集的列會是這樣的:

| YEAR | GOLD | SILVER | BRONZE | TOTAL | 

我能,銀,銅獎成員分別採用以下3個查詢得到每年不同的計數黃金:

SELECT YEAR(JoinDate) AS YEAR, COUNT(*) AS GOLD FROM Members 
WHERE Level=1 GROUP BY YEAR(JoinDate) ORDER BY YEAR(JoinDate) 

SELECT YEAR(JoinDate) AS YEAR, COUNT(*) AS SILVER FROM Members 
WHERE Level=2 GROUP BY YEAR(JoinDate) ORDER BY YEAR(JoinDate) 

SELECT YEAR(JoinDate) AS YEAR, COUNT(*) AS BRONZE FROM Members 
WHERE Level=3 GROUP BY YEAR(JoinDate) ORDER BY YEAR(JoinDate) 

我也可以用類似的查詢獲得總計:

SELECT YEAR(JoinDate) AS YEAR, COUNT(*) AS TOTAL FROM Members 
GROUP BY YEAR(JoinDate) ORDER BY YEAR(JoinDate) 

我的問題是我還沒有找到一種方法來簡化所有這些到一個查詢。這是如何完成的?

回答

3

你在尋找什麼叫做交叉表查詢或數據透視表。

這應該爲你做吧..

SELECT  YEAR(JoinDate) YEAR, 
      SUM(CASE [Level] WHEN 1 THEN 
        1 ELSE 0 END) Gold, 
      SUM(CASE [Level] WHEN 2 THEN 
        1 ELSE 0 END) Silver, 
      SUM(CASE [Level] WHEN 3 THEN 
        1 ELSE 0 END) Bronze, 
     COUNT([Level]) Total 
FROM  members 
GROUP BY YEAR(JoinDate) 
ORDER BY YEAR(JoinDate) 

更多交叉表查詢上here

1

簡單的方法是:

SELECT YEAR(JoinDate) AS YEAR, 
    SUM(case when Level = 1 then 1 else 0 end) AS GoldCount, 
    SUM(case when Level = 2 then 1 else 0 end) AS SilverCount, 
    SUM(case when Level = 3 then 1 else 0 end) AS BronzeCount 
FROM Members 
GROUP BY YEAR(JoinDate) ORDER BY YEAR(JoinDate) 
1

而且總添加到朱麗葉的答案,只需添加COUNT(*)

SELECT YEAR(JoinDate) AS YEAR,  
    SUM(case when Level = 1 then 1 else 0 end) AS GoldCount,  
    SUM(case when Level = 2 then 1 else 0 end) AS SilverCount,  
    SUM(case when Level = 3 then 1 else 0 end) AS BronzeCount, 
    Count(*) TotalCount 
FROM Members 
GROUP BY YEAR(JoinDate) 
ORDER BY YEAR(JoinDate)