如何从SQL查询进行布局

时间:2017-08-30 13:00:44

标签: sql sql-server tsql

我有这样的选择查询(视图):

SELECT ArticleID, period, SUM(Amount) As Total 
FROM atbv_Accounting_OrdersDeliveries 
WHERE InvoiceNo IS NOT NULL 
GROUP BY ArticleID, period

这让我回答:

enter image description here

是否可以编写一个返回数据的select语句:

enter image description here

2 个答案:

答案 0 :(得分:1)

我这里没有一个sql server来测试它,但应该是这样的:

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME(period)
FROM (SELECT DISTINCT period FROM atbv_Accounting_OrdersDeliveries WHERE InvoiceNo IS NOT NULL) AS periods

SET @DynamicPivotQuery = 
  N'SELECT , ' + @ColumnName + '
    FROM (SELECT
    ArticleID, period, Amount
    FROM atbv_Accounting_OrdersDeliveries 
    WHERE InvoiceNo IS NOT NULL 
    ) AS T
    PIVOT(SUM(Amount) 
          FOR period IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

有关MS Sql Server的更多信息,请访问here

答案 1 :(得分:1)

你可以这样做:

修改

SELECT ArticleID, [201701], [201702], [201703], [201708]
FROM
(
    SELECT *
    FROM atbv_Accounting_OrdersDeliveries 
    WHERE InvoiceNo IS NOT NULL 
) T
PIVOT
(
  SUM(Amount)
  FOR period IN ([201701], [201702], [201703], [201708])
) P;