任何人都可以帮我写一个查询来获得以下结果。
表格如下:
Table1
------------
Col1 Col2
=== ====
A Error
B Success
C Success
D Success
这是查询的结果(使用Join
语句后):
Success Error
-------- ------
B A
C A
D A
预期结果:
Success Error
B A
C 0
D 0
Col2
中的值可能会有所不同 - 如下所述。
Col1 Col2
---- -----
A Error
B Success
C Success
D Failed
E Unknown
F Success
G Error
预期结果:
Success Failed Error Unknown
------- ------ ----- -------
B D A E
C 0 G 0
F 0 0 0
我正在尝试将第二列中的值作为新表中的标题,将第一列中的值作为新表中的行值。
这是我的SQL代码:
Select tb1.Col1 as Success, tb2.Col1 as Error
from ( Select * from table1 where Col2 = 'Success') tb1
Join ( Select * from table1 where Col2 = 'Error') tb2
on tb1.Col1 is not NUll
答案 0 :(得分:2)
您只是希望获得彼此相邻的项目列表,而它们之间没有任何实际关系?使用row_number这样的东西应该可以工作:
select
max(case when col2 = 'Success' then col1 else null end) as Success,
max(case when col2 = 'Failed' then col1 else null end) as Failed,
max(case when col2 = 'Error' then col1 else null end) as Error,
max(case when col2 = 'Unknown' then col1 else null end) as Unknown
from (
select
col2,
col1,
row_number() over (partition by col2 order by col1) as rn
from
data
) TMP
group by RN
答案 1 :(得分:0)
我认为@JamesZ
的回答是正确的,但如果OP需要Col2
动态值的结果,我建议使用以下代码:
Declare @query nvarchar(max) = ''
select @query = @query + ', isnull(max(case when col2 = ''' + Col2 + ''' then col1 else null end), 0) as ' + Col2
from (select distinct Col2 from temptable) dt
set @query = 'select ' + substring(@query, 2, len(@query)) +
' from (select col2, col1, row_number() over (partition by col2 order by col1) as rn from temptable) TMP group by RN'
exec(@query)
结果列现在等待各种Col2
:
Error | Failed | Success | Unknown
------+--------+---------+-------------
A | D | B | E
G | 0 | C | 0
0 | 0 | F | 0
答案 2 :(得分:0)
这是标准的透视任务:
Create table t(code char(1), status nvarchar(10))
Insert into t values
( 'A', 'Error'),
( 'B', 'Success'),
( 'C', 'Success'),
( 'D', 'Failed'),
( 'E', 'Unknown'),
( 'F', 'Success'),
( 'G', 'Error')
;with cte as (Select *, row_number() over(partition by status order by code) c from t)
Select success, failed, error, unknown from cte
Pivot(max(code) for status in([error],[failed],[unknown],[success])) p