SQL Dynamic Pivot

时间:2013-11-27 09:20:36

标签: sql sql-server pivot

我编写了一个动态SQL Pivot查询,它返回每天的数量,返回的列数是动态的,基于打开参数之间的天数。我遇到的问题是Columns不在DateOrder中,我猜我需要一些表格或Order By来解决这个问题,有没有人有任何想法我需要把它放进去?

    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

    --declare and set variables
    DECLARE @v_Columns VARCHAR(MAX)
    ,@v_StartDate DATETIME = GETDATE() - 10
    ,@v_EndDate DATETIME = GETDATE()
    ,@v_Query VARCHAR(max)

--select results
SELECT @v_Columns = Coalesce(@v_Columns, '[') + convert(VARCHAR, cast(DateCreated AS DATE), 111) + '],['
FROM (
    SELECT DISTINCT cast(DateCreated AS DATE) AS DateCreated
    FROM TransactionOriginTracking
    ) tot
WHERE tot.DateCreated BETWEEN @v_StartDate
        AND @v_EndDate

SET @v_Columns = SUBSTRING(@v_Columns, 1, Len(@v_Columns) - 2)
SET @v_Query = 'select
    *
from
(
SELECT
    cast(Tracking.DateCreated as date) as [Date],
    th.TotalQuantity [Quantity]
FROM
    TransactionHeader th
    Inner JOin TransactionOriginTracking as Tracking on Tracking.TransactionHeaderId = th.Id
        and Tracking.WorkflowStageId = 9
    Inner Join CompanyDivision on CompanyDivision.Id = th.CompanyDivisionId
WHERE
    Tracking.DateCreated between ''' + CONVERT(VARCHAR(50), @v_StartDate, 111) + ''' AND ''' + CONVERT(VARCHAR(50), @v_EndDate, 111) + '''
) as src
Pivot
(
SUM(src.Quantity)
For src.Date IN (' + @v_Columns + ')
) as PivotView'

EXEC (@v_Query)

1 个答案:

答案 0 :(得分:1)

在构建列列表时,按日期排序:

--select results
SELECT 
    @v_Columns = Coalesce(@v_Columns, '[') + convert(VARCHAR, cast(DateCreated AS DATE), 111) + '],['
FROM 
    (SELECT DISTINCT 
         CAST(DateCreated AS DATE) AS DateCreated
     FROM 
         TransactionOriginTracking) tot
WHERE 
    tot.DateCreated BETWEEN @v_StartDate AND @v_EndDate
ORDER BY 
    tot.DateCreated