在SQL中总结多个值

时间:2016-01-21 09:33:49

标签: sql sql-server tsql

我使用以下SQL代码来获取一年中每个季度的预订次数:

SELECT 
    Year, 
    ISNULL(QPivot.[1],0) As [Quater 1], 
    ISNULL(QPivot.[2],0) As [Quater 2], 
    ISNULL(QPivot.[3],0) As [Quater 3], 
    ISNULL(QPivot.[4],0) As [Quater 4] 
FROM 
    (SELECT 
         YEAR(checkInDate) [Year], 
         DATEPART(QUARTER, checkInDate) [Quarter], 
         COUNT(1) [Reservation Count] 
     FROM 
         ReservationRoom  
     GROUP BY 
         YEAR(checkInDate), DATEPART(QUARTER, checkInDate)) AS QuarterlyData 
PIVOT(SUM([Reservation Count]) 
FOR QUARTER IN ([1],[2],[3],[4])) AS QPivot

这是我从该查询得到的结果:

[my result

但是现在我想添加一列[Total],它总结了一年中所有季度的所有价值。例如,2015年是1年,2016年是8年。

任何人都可以帮我吗?

2 个答案:

答案 0 :(得分:1)

尝试将四个季度加在一起:

SELECT t.Year, t.[Quarter 1], t.[Quarter 2], t.[Quarter 3], t.[Quarter 4],
    (t.[Quarter 1] + t.[Quarter 2] + t.[Quarter 3] + t.[Quarter 4]) AS Total
FROM
(
    SELECT Year, ISNULL(QPivot.[1],0) As [Quater 1], ISNULL(QPivot.[2],0) As [Quater 2],
        ISNULL(QPivot.[3],0) As [Quater 3], ISNULL(QPivot.[4],0) As [Quater 4],
    FROM
    (
        SELECT YEAR(checkInDate) [Year], DATEPART(QUARTER, checkInDate) [Quarter], COUNT(1) [Reservation Count] 
        FROM ReservationRoom  
        GROUP BY YEAR(checkInDate), DATEPART(QUARTER,checkInDate)) AS QuarterlyData
        PIVOT( SUM([Reservation Count]) 
        FOR QUARTER IN ([1],[2],[3],[4])
    ) AS QPivot
) t

答案 1 :(得分:1)

我通常发现有点难以阅读的数据透视查询。你的查询所做的就是每年有一个结果行(所以逐年分组)和计数季度和总数(所以有一些计数表达式)。查询可以很容易地写成:

select 
  year(checkindate) as year, 
  count(case when datepart(quarter, checkindate) = 1 then 1 end) as q1,
  count(case when datepart(quarter, checkindate) = 2 then 1 end) as q2,
  count(case when datepart(quarter, checkindate) = 3 then 1 end) as q3,
  count(case when datepart(quarter, checkindate) = 4 then 1 end) as q4,
  count(*) as total
from reservationroom  
group by year(checkindate)
order by year(checkindate);