gpt4 book ai didi

sql - 如何在 MS Access 2007 或 MS SQL Server 2005 中通过 SQL 将字段转换为行

转载 作者:行者123 更新时间:2023-12-01 12:02:00 25 4
gpt4 key购买 nike

我有一个遗留的 MS Access 2007 表,其中包含 52 个字段(一年中的每周 1 个字段)代表历史销售数据(加上一个实际年份的字段)。我想将该数据库转换为更传统的时间/值(value)列表。

有谁知道如何在不使用超过 52 个显式参数编写查询的情况下做到这一点?

(如果MS SQL Server 2005下有解决方案,我也可以导出/导入表)

最佳答案

Using PIVOT and UNPIVOT .

UNPIVOT performs almost the reverse operation of PIVOT, by rotating columns into rows. Suppose the table produced in the previous example is stored in the database as pvt, and you want to rotate the column identifiers Emp1, Emp2, Emp3, Emp4, and Emp5 into row values that correspond to a particular vendor. This means that you must identify two additional columns. The column that will contain the column values that you are rotating (Emp1, Emp2,...) will be called Employee, and the column that will hold the values that currently reside under the columns being rotated will be called Orders. These columns correspond to the pivot_column and value_column, respectively, in the Transact-SQL definition. Here is the query.

--Create the table and insert values as portrayed in the previous example.
CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,
Emp3 int, Emp4 int, Emp5 int)
GO
INSERT INTO pvt VALUES (1,4,3,5,4,4)
INSERT INTO pvt VALUES (2,4,1,5,5,5)
INSERT INTO pvt VALUES (3,4,3,5,4,4)
INSERT INTO pvt VALUES (4,4,2,5,5,4)
INSERT INTO pvt VALUES (5,5,1,5,5,5)
GO
--Unpivot the table.
SELECT VendorID, Employee, Orders
FROM
(SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
FROM pvt) p
UNPIVOT
(Orders FOR Employee IN
(Emp1, Emp2, Emp3, Emp4, Emp5)
)AS unpvt
GO

Here is a partial result set.

VendorID   Employee   Orders
1 Emp1 4
1 Emp2 3
1 Emp3 5
1 Emp4 4
1 Emp5 4
2 Emp1 4
2 Emp2 1
2 Emp3 5
2 Emp4 5
2 Emp5 5
...

关于sql - 如何在 MS Access 2007 或 MS SQL Server 2005 中通过 SQL 将字段转换为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/334571/

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