2011-12-07 50 views
3

我有下面的查詢,它返回在2011年的StackOverflow每天的問題的數量。我想要得到2011年期間所有問題的總和。爲此,我使用ROLLUP如何在新列中顯示彙總數據?

select 
    year(p.CreationDate) as [Year], 
    month(p.CreationDate) as [Month], 
    day(p.CreationDate) as [Day], 
    count(*) as [QuestionsAskedToday] 
from Posts p 
    inner join PostTags pt on p.id = pt.postid 
    inner join Tags t on t.id = pt.tagid 
where 
    t.tagname = 'android' and 
    p.CreationDate > '2011-01-01 00:00:00' 
group by year(p.CreationDate), month(p.CreationDate),day(p.CreationDate) 
​with rollup 
order by year(p.CreationDate), month(p.CreationDate) desc,day(p.CreationDate) desc​ 

這是輸出:

output

2011年的每一天提出的所有問題和被顯示在QuestionsAskedToday列本身。

有沒有辦法在別名中顯示新列的彙總?

Link to the query

回答

1

你可以採取這樣的做法:Example

SELECT 
    YEAR(p.CreationDate) AS 'Year' 
    , CASE 
     WHEN GROUPING(MONTH(p.CreationDate)) = 0 
      THEN CAST(MONTH(p.CreationDate) AS VARCHAR(2)) 
     ELSE 'Totals:' 
    END AS 'Month' 
    , CASE 
     WHEN GROUPING(DAY(p.CreationDate)) = 0 
     THEN CAST(DAY(p.CreationDate) AS VARCHAR(2)) 
     ELSE 'Totals:' 
    END AS [DAY] 
    , CASE 
     WHEN GROUPING(MONTH(p.CreationDate)) = 0 
      AND GROUPING(DAY(p.CreationDate)) = 0 
       THEN COUNT(1) 
    END AS 'QuestionsAskedToday' 
    , CASE 
     WHEN GROUPING(MONTH(p.CreationDate)) = 1 
      OR GROUPING(DAY(p.CreationDate)) = 1 
       THEN COUNT(1) 
    END AS 'Totals' 
FROM Posts AS p 
INNER JOIN PostTags AS pt ON p.id = pt.postid 
INNER JOIN Tags AS t ON t.id = pt.tagid 
WHERE t.tagname = 'android' 
    AND p.CreationDate >= '2011-01-01' 
GROUP BY ROLLUP(YEAR(p.CreationDate) 
    , MONTH(p.CreationDate) 
    , DAY(p.CreationDate)) 
ORDER BY YEAR(p.CreationDate) 
    , MONTH(p.CreationDate) DESC 
    , DAY(p.CreationDate) DESC​​​​​​​ 

如果這是你想要的東西,同樣的技術可以應用到Years,以及以總他們在新列,或他們自己的專欄,如果你想查詢多年並聚合它們。

+0

這就是我想要的。謝謝。 – Animesh

2

要將此顯示爲列而不是一行,您可以使用SUM(COUNT(*)) OVER()而不是ROLLUP。 (Online Demo

SELECT YEAR(p.CreationDate) AS [Year], 
     MONTH(p.CreationDate) AS [Month], 
     DAY(p.CreationDate) AS [Day], 
     COUNT(*)    AS [QuestionsAskedToday], 
     SUM(COUNT(*)) OVER() AS [Total] 
FROM Posts p 
     INNER JOIN PostTags pt 
     ON p.id = pt.postid 
     INNER JOIN Tags t 
     ON t.id = pt.tagid 
WHERE t.tagname = 'android' 
     AND p.CreationDate > '2011-01-01 00:00:00' 
GROUP BY YEAR(p.CreationDate), 
      MONTH(p.CreationDate), 
      DAY(p.CreationDate) 
ORDER BY YEAR(p.CreationDate), 
      MONTH(p.CreationDate) DESC, 
      DAY(p.CreationDate) DESC