我有一个表CheckSheet_fault,其中包含两列数据,如下所示
CheckSheet_No | Fault |
1 A
1 B
1 C
2 A
2 C
如何使用SQL在目标表中实现以下结果?
CheckSheet_No | Fault 1 | Fault 2 | Fault 3
1 A B C
2 A C
我可以在目标表中添加最多10个Fault列。我的目标是不重复检查表编号。
由于 干杯, Rushir
答案 0 :(得分:3)
检查是否有效
SELECT CheckSheet_No,
MAX(CASE WHEN rn=1 THEN Fault END) As Fault1,
MAX(CASE WHEN rn=2 THEN Fault END) As Fault2,
MAX(CASE WHEN rn=3 THEN Fault END) As Fault3
FROM
(
SELECT CheckSheet_No,Fault,
Row_Number() Over(Partition By CheckSheet_No Order By Fault) as rn
FROM CheckSheet_fault
) Z
GROUP BY Z.CheckSheet_No
答案 1 :(得分:0)
如果你有三列以上,请试试这个。
CREATE Table #table1 (CheckSheet_No int,Fault varchar(1))
insert INTO #table1 values(1,'A')
insert INTO #table1 values(1,'B')
insert INTO #table1 values(1,'C')
insert INTO #table1 values(2,'A')
insert INTO #table1 values(2,'C')
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SELECT @cols=stuff((
SELECT ', ' + MAX(fault)
FROM #table1
group by fault
order by fault
FOR XML PATH('')), 1, 2, '');
SET @query = 'SELECT CheckSheet_No, ' + @cols + '
from
(
SELECT #table1.CheckSheet_No,Fault FROM #table1
) x
pivot
(
MAX(Fault)
for x.Fault in (' + @cols + ')
) p'
execute sp_executesql @query;