具有多个小计的SQL动态数据透视查询

时间:2016-12-30 10:01:53

标签: sql tsql

对于下面的代码,我能够使用subtotal创建一个动态数据透视。但我需要在此代码中再添加一个小计列。它必须是 NUM_TO_EXIT 值的总和。如您可以看到图片2,我在动态数据透视中的动态日期中使用了 NUM_TO_ENTER ,但我无法仅为总值 NUM_TO_EXIT 。我尝试了一切,但无法做到这一点。感谢yor支持。我正在使用MSSQL 2008 R2。

  DIRECTIONAL_METRIC_ID ZONE_ID START_TIME  END_TIME    RECEIVED_TS STATUS  NUM_TO_ENTER    NUM_TO_EXIT DAY_OF_WEEK_ID  TIME_ID
436909  254 2016-02-06 10:00:00.000 2016-02-06 10:00:00.000 2016-02-06 10:00:00.000 1   195 195 7   300
436910  254 2016-02-07 10:00:00.000 2016-02-07 10:15:00.000 2016-02-07 10:15:00.000 1   195 195 7   300
436911  278 2016-02-01 10:00:00.000 2016-02-01 10:15:00.000 2016-02-01 10:15:00.000 1   95  95  7   300
436912  278 2016-02-02 10:00:00.000 2016-02-02 10:15:00.000 2016-02-02 10:15:00.000 1   95  95  7   300
436913  278 2016-02-03 10:00:00.000 2016-02-03 10:15:00.000 2016-02-03 10:15:00.000 1   95  95  7   300

What I need

Structe of DIRECTIONAL_METRIC TABLE

DECLARE @mydate DATETIME
SELECT @mydate = GETDATE()

IF OBJECT_ID('tempdb..#Dates') IS NOT NULL
drop table #Dates


SELECT DISTINCT CONVERT(VARCHAR,START_TIME,106) AS [Date]
INTO #Dates
FROM dbo.DIRECTIONAL_METRIC
WHERE CAST(START_TIME as DATE) >=CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@mydate)-1),@mydate),101)
and CAST(START_TIME as DATE) < @mydate
AND DATEPART(HOUR,START_TIME) BETWEEN 9 AND 23
order by [Date]

DECLARE @cols VARCHAR(1000)
SELECT @cols = COALESCE (@cols + ',[' + [Date] +']','[' + [Date] + ']')
FROM #Dates


DECLARE @GrandTotalCol  NVARCHAR (MAX)
SELECT @GrandTotalCol = COALESCE (@GrandTotalCol + 'ISNULL ([' + [Date] +'],0) + ', 'ISNULL([' + [Date]+ '],0) + ')
FROM #Dates 
ORDER BY [Date]
SET @GrandTotalCol = LEFT (@GrandTotalCol, LEN (@GrandTotalCol)-1)

DECLARE @qry varchar(4000)
SET @qry =

'
DECLARE @mydate DATETIME
SELECT @mydate = GETDATE()

SELECT *, ('+ @GrandTotalCol + ') 
AS [Grand Total] INTO #temp_MatchesTotal 
FROM 
(
        SELECT ZO.CODE AS KOD,
        convert(varchar, START_TIME, 106) AS [Date],
        SUM(NUM_TO_ENTER) AS NUM_TO_ENTER
        FROM  dbo.DIRECTIONAL_METRIC AS z INNER JOIN ZONE AS ZO ON z.ZONE_ID=ZO.ZONE_ID
        WHERE CAST(START_TIME as DATE) >=CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@mydate)-1),@mydate),101)
        and CAST(START_TIME as DATE) < @mydate
        and DATEPART(HOUR,START_TIME) between 9 and 23
        AND ZO.CODE IS NOT NULL
        group by ZO.CODE,convert(varchar, START_TIME, 106)
) P
PIVOT
( 
         SUM(NUM_TO_ENTER) 
         FOR  [Date] IN(' +@cols + ')
)
 AS pvt
ORDER BY KOD
SELECT * FROM #temp_MatchesTotal 
DROP TABLE #temp_MatchesTotal'


EXEC(@qry)
GO

0 个答案:

没有答案