Sql 具有多个聚合值的透视表
我试图在桌子下面旋转,这可能吗 但如果我通过代码聚合它们,值A或B将因此消失 从 名称 代码 价值 凯文 代码1 A. 凯文 代码1 B 凯文 代码2 C 凯文 代码3 D 汤姆 代码1 E 汤姆 代码2 F 汤姆 代码3 GSql 具有多个聚合值的透视表,sql,sql-server,tsql,pivot,Sql,Sql Server,Tsql,Pivot,我试图在桌子下面旋转,这可能吗 但如果我通过代码聚合它们,值A或B将因此消失 从 名称 代码 价值 凯文 代码1 A. 凯文 代码1 B 凯文 代码2 C 凯文 代码3 D 汤姆 代码1 E 汤姆 代码2 F 汤姆 代码3 G 这是一个固定列列表版本。您应该使用此模板构建动态的 select Name , first_value(Code1) over(partition by Name order by rn) Code1 , first_value(Code2) over(part
这是一个固定列列表版本。您应该使用此模板构建动态的
select Name
, first_value(Code1) over(partition by Name order by rn) Code1
, first_value(Code2) over(partition by Name order by rn) Code2
, first_value(Code3) over(partition by Name order by rn) Code3
from (
select t.* , row_number() over(partition by Name, Code order by Value) rn
from tbl t
) t
pivot (max(value) for code in (Code1, Code2, Code3)) p
order by Name;
使用行数()
和一些算术:
select name,
max(case when code = 'Code1' then value end) as code1,
max(case when code = 'Code2' then value end) as code2,
max(case when code = 'Code3' then value end) as code3
from (select t.*,
row_number() over (partition by name, code order by (select null)) as seqnum
from t
) t
group by name, seqnum;
不清楚动态SQL是由于动态列数还是试图解决此问题。但这也适用于动态SQL。我认为这不是pivot函数的概念。Code1是一个值或一个键-要么对其执行聚合,要么以与使用名称相同的方式使用它。我将first_value函数更改为max as first_value,因为没有为同一代码返回每个值。