如何在新列中显示汇总数据?

时间:2011-12-07 17:07:53

标签: tsql rollup

我有以下查询,它在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

2 个答案:

答案 0 :(得分: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            

答案 1 :(得分: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以及在新列或它们自己的列中总计它们,如果你想查询多年并聚合它们。 / p>