gpt4 book ai didi

日期列上的 SQL 数据透视表?

转载 作者:行者123 更新时间:2023-12-04 20:52:50 26 4
gpt4 key购买 nike

我对 SQL 相当陌生,但相信我,我在发布之前已经搜索过帮助。

我有一个查询,它返回分配给工作的人员列表,工作的长度也各不相同,分配给这些工作的人员的工作长度也不同。

我想要做的是转换什么是类似记录的列表,唯一的变量是日期,以及一些如何旋转这些数据,以便日期成为列标题,而行表示 BOOL 是/否。

这是我目前正在取回的数据。 JSON 编码
{"results":[{"role":"Vision Supervisor","familyname":"Unsworth","givenname":"Simon","skill":"10","level":"Telegenic Staff","id":"664","date":"2013-03-27"},{"role":"Vision Supervisor","familyname":"Unsworth","givenname":"Simon","skill":"10","level":"Telegenic Staff","id":"664","date":"2013-03-26"},{"role":"Vision Supervisor","familyname":"Unsworth","givenname":"Simon","skill":"10","level":"Telegenic Staff","id":"664","date":"2013-03-25"},{"role":"Vision Supervisor","familyname":"Unsworth","givenname":"Simon","skill":"10","level":"Telegenic Staff","id":"664","date":"2013-03-24"}]}
我想回来的是:
{"results":[{"role":"Vision Supervisor","familyname":"Unsworth","givenname":"Simon","skill":"10","level":"Telegenic Staff","id":"664","2013-03-27":"YES","2013-03-26":"YES","2013-03-25":"YES","2013-03-24":"YES"}]}
我确定这是某种 PIVOT 查询,但我无法让它工作。

谢谢

最佳答案

如果要在 SQL Server 中运行此查询,则可以使用 PIVOT功能:

select *
from
(
select role, familyname, givenname, skill,
level, id, date, 'Y' flag
from yourtable
) src
pivot
(
max(flag)
for date in ([2013-03-27], [2013-03-26],
[2013-03-25], [2013-03-24])
) piv

SQL Fiddle with Demo

或者您可以使用聚合函数和 CASE陈述:
select role, familyname, givenname, skill,
level, id,
max(case when date = '2013-03-27' then flag end) '2013-03-27',
max(case when date = '2013-03-26' then flag end) '2013-03-26',
max(case when date = '2013-03-25' then flag end) '2013-03-25',
max(case when date = '2013-03-24' then flag end) '2013-03-24'
from
(
select role, familyname, givenname, skill,
level, id, date, 'Y' flag
from yourtable
) src
group by role, familyname, givenname, skill,
level, id

SQL Fiddle with Demo

两者都给出了结果:
|              ROLE | FAMILYNAME | GIVENNAME | SKILL |           LEVEL |  ID | 2013-03-27 | 2013-03-26 | 2013-03-25 | 2013-03-24 |
----------------------------------------------------------------------------------------------------------------------------------
| Vision Supervisor | Unsworth | Simon | 10 | Telegenic Staff | 664 | Y | Y | Y | Y |

如果您知道要转置的值,则上述方法效果很好,但是如果您不知道,则可以使用类似于以下内容的动态 sql:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(convert(char(10), date, 120))
from yourtable
group by date
order by date desc
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')

set @query = 'SELECT role, familyname, givenname, skill,
level, id,' + @cols + ' from
(
select role, familyname, givenname, skill,
level, id, date, ''Y'' flag
from yourtable
) x
pivot
(
max(flag)
for date in (' + @cols + ')
) p '

execute(@query)

SQL Fiddle with Demo

关于日期列上的 SQL 数据透视表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13977241/

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