SQL 透视/反透视?
Posted
技术标签:
【中文标题】SQL 透视/反透视?【英文标题】:SQL pivot/Unpivot? 【发布时间】:2020-09-29 09:35:49 【问题描述】:真的希望有人可以帮助我,我的表格结构如下:
检索此数据的查询是:
SELECT
[Pattern Number]
,Sunday
,Monday
,Tuesday
,Wednesday
,Thursday
,Friday
,Saturday
FROM Access.Pattern_Details
WHERE [Pattern Number] = 4
+----------------+--------+--------+---------+-----------+----------+--------+----------+
| Pattern Number | Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday |
+----------------+--------+--------+---------+-----------+----------+--------+----------+
| 4 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
+----------------+--------+--------+---------+-----------+----------+--------+----------+
我想变成这样:
+----------------+------------+-----------+
| Pattern Number | WorkingDay | Day |
+----------------+------------+-----------+
| 4 | 0 | Sunday |
| 4 | 1 | Monday |
| 4 | 1 | Tuesday |
| 4 | 1 | Wednesday |
| 4 | 1 | Thursday |
| 4 | 1 | Friday |
| 4 | 0 | Saturday |
+----------------+------------+-----------+
我已经尝试过PIVOT
/UNPIVOT
,这感觉是正确的方向,但我真的很想知道如何获得结果:(
【问题讨论】:
您好 Cordy,请在您的问题中包含您尝试过的查询。 请用您正在运行的数据库标记您的问题:mysql、oracle、postgresql...?答案取决于供应商。 UNION ALL 是一种简单的方法。 如果您尝试过某事并遇到问题,请展示该内容并描述该问题。 “真正为如何获得结果而苦苦挣扎”并不是读者可以做任何事情的描述 【参考方案1】:在 SQL Server 中,我会推荐cross apply
和values()
:
select pd.[Pattern Number], x.*
from Access.Pattern_Details pd
cross apply (values
('Sunday', Sunday),
('Monday', Monday),
('Tuesday', Tuesday),
('Wednesday', Wednesday),
('Thursday', Thursday),
('Friday', Friday),
('Saturday', Saturday)
) x(day, workingDay)
where pd.[Pattern Number] = 4
【讨论】:
【参考方案2】:你可以使用UNPIVOT
:
SELECT [Pattern Number], [Working Day], [Day]
FROM
(
SELECT 4 [Pattern Number], 0 Sunday, 1 Monday, 1 Tuesday, 1 Wednesday, 1 Thursday, 1 Friday, 0 Saturday
) pvt
UNPIVOT([Working Day] FOR [Day] IN ([Sunday], [Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday])) unpvt
db<>fiddle
UNPIVOT
有很好的文档和解释。见:Using Pivot and Unpivot - SQL Server
【讨论】:
以上是关于SQL 透视/反透视?的主要内容,如果未能解决你的问题,请参考以下文章