gpt4 book ai didi

sql-server - SQL Server 枢轴 : Displaying row values to column headers

转载 作者:行者123 更新时间:2023-12-03 23:03:49 31 4
gpt4 key购买 nike

我有一个表格(项目),其格式如下:

ITEMNO | WEEKNO | VALUE  
A1234 | 1 | 805
A2345 | 2 | 14.50
A3547 | 2 | 1396.70
A2208 | 1 | 17.65
A4326 | 6 | 19.99

这是一个表格,显示给定一周内商品的销售额。

结果或我想以表格格式显示的是一行中的项目编号,然后是每周包含值的列,例如
ITEMNO | WK1 | WK2 | WK3 | WK4 | WK5  ...etc up to 52  
A1234 | 805 | 345 | 234 | 12 | 10 ...etc up to 52
A2345 | 23 | 12 | 456 | 34 | 99 ...etc up to 52
A3456 | 234 | 123 | 34 | 25 | 190 ...etc up to 52

虽然我有 52 岁……所以我只有最多第 9 周的数据,但这会随着时间的推移而增加。

所以基本上我想要显示的是作为列标题的周数值。

这可能吗...虽然我很想通过代码/(asp.net)获取数据并正确显示,但我想知道是否可以在SQL中像这样显示它?

有谁知道或认为这可能是最好的方法?

最佳答案

使用静态 SQL 和动态 SQL 有两种方法可以做到这一点:

静态枢轴:

SELECT P.ItemNo, IsNull(P.[1], 0) as Wk1, IsNull(P.[2], 0) as Wk2
, IsNull(P.[3], 0) as Wk3, IsNull(P.[4], 0) as Wk4
, IsNull(P.[5], 0) as Wk5, IsNull(P.[6], 0) as Wk6
, IsNull(P.[7], 0) as Wk7, IsNull(P.[8], 0) as Wk8
, IsNull(P.[9], 0) as Wk9
FROM
(
SELECT ItemNo, WeekNo, [Value]
FROM dbo.Items
) I
PIVOT
(
SUM([Value])
FOR WeekNo IN ([1], [2], [3], [4], [5], [6], [7], [8], [9])
) as P

动态枢轴:
DECLARE
@cols AS NVARCHAR(MAX),
@y AS INT,
@sql AS NVARCHAR(MAX);

-- Construct the column list for the IN clause
SET @cols = STUFF(
(SELECT N',' + QUOTENAME(w) AS [text()]
FROM (SELECT DISTINCT WeekNo AS W FROM dbo.Items) AS W
ORDER BY W
FOR XML PATH('')),
1, 1, N'');


-- Construct the full T-SQL statement
-- and execute dynamically
SET @sql = N'SELECT *
FROM (SELECT ItemNo, WeekNo, Value
FROM dbo.Items) AS I
PIVOT(SUM(Value) FOR WeekNo IN(' + @cols + N')) AS P;';

EXEC sp_executesql @sql;
GO

关于sql-server - SQL Server 枢轴 : Displaying row values to column headers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9585094/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com