我有这样的选择查询(视图):
SELECT ArticleID, period, SUM(Amount) As Total
FROM atbv_Accounting_OrdersDeliveries
WHERE InvoiceNo IS NOT NULL
GROUP BY ArticleID, period
这让我回答:
是否可以编写一个返回数据的select语句:
答案 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;