gpt4 book ai didi

sql - 数据透视表行到列

转载 作者:行者123 更新时间:2023-12-04 23:44:05 25 4
gpt4 key购买 nike

我正在使用 SQLServer2008 Express
我有一个表和一个脚本,用于将行转换为具有预期结果的列

PARENT_ID   name01  name02  name03  name04  
1 ABC DEF ABC2 DEF2
2 DEF3 null null null

但是,我得到的结果是

PARENT_ID    name01    name02    name03    name04  
1 ABC DEF ABC2 DEF2
2 null null null null

我知道代码有问题,只是我想不通。希望有人能帮忙。

CREATE TABLE #temp (
parent_id bigint NOT NULL
,dependent_id bigint not null
,date_of_birth date not null
,last_name varchar(100)
,first_name varchar(100)
,effective_start_date date
,effective_end_Date date
)
insert into #temp values (1,1,'1990-10-01','ABC',null,'1989-01-01','9999-12-31')
insert into #temp values (1,2,'1991-06-02','DEF',null,'1989-01-01','9999-12-31')
insert into #temp values (1,3,'1992-06-02','ABC2',null,'1989-01-01','9999-12-31')
insert into #temp values (1,4,'1993-06-02','DEF2',null,'1989-01-01','9999-12-31')
insert into #temp values (2,5,'2000-06-02','DEF3',null,'1989-01-01','9999-12-31')

SELECT PARENT_ID
,[1] as name01
,[2] as name02
,[3] as name03
,[4] as name04
FROM ( SELECT top(100) percent
PARENT_ID
, dependent_id
, (isnull(first_name,'')+last_name) as fullname
FROM #temp
where GETDATE() between effective_start_date and effective_end_Date
order by date_of_birth
) AS piv
PIVOT ( max(fullname)
FOR dependent_id IN ([1], [2], [3], [4])
) AS chld

谢谢埃尔默

最佳答案

我认为是数据而不是代码有问题。您要插入 5 作为 dependent_id 但希望它出现在 1 列中?

你也许可以使用 dependent_id % 4 但我不确定这里的意图是什么?

编辑 根据您的评论,我认为您需要这个?

SELECT PARENT_ID  
,[1] as name01
,[2] as name02
,[3] as name03
,[4] as name04
FROM
(
SELECT
PARENT_ID,
ROW_NUMBER() OVER (PARTITION BY PARENT_ID ORDER BY date_of_birth) AS RN
, (isnull(first_name,'')+last_name) as fullname
FROM #temp
where GETDATE() between effective_start_date and effective_end_Date
) AS piv
PIVOT ( max(fullname)
FOR RN IN ([1], [2], [3], [4])
) AS chld

关于sql - 数据透视表行到列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3387405/

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