Cap*_*in0 1 sql sql-server pivot sql-server-2008 pivot-without-aggregate
请帮我解决一下这个.我完全陷入困境.我有编码器块或什么的.
我有下表
ID Name Cost Included
---- ---------- ------- ----------
1 Package1 10.00 Yes
2 Package2 20.00 No
3 Package3 20.00 Yes
Run Code Online (Sandbox Code Playgroud)
我想交叉显示这些信息,要显示如下例子,表格中会有更多列.
Type Package1 Package2 Package3
----- ------------ ----------- ----------
Name Package1 Package2 Package3
Cost 10.00 20.00 30.00
Included Yes No Yes
Run Code Online (Sandbox Code Playgroud)
在我看来,您正在尝试构建产品比较列表.如果是这样,您可以先将表格取消,然后将各个记录连接在一起.
'transponded'部分对列进行疏忽.所有列必须是兼容类型或转换为一个.我选择varchar(100).transponded返回表,包含三列,来自ProductInfo的ID,Type作为列名,Value作为相应列的值.
通过添加另一个选择部件将所需产品的信息连接在一起left join transponded tn on t1.Type = tnType and tn.ID = @parametern.这部分似乎很麻烦,但是当我尝试使用pivot执行此部分时,我无法按正确的顺序获取列 - 在Type中透视排序的名称.但是它需要动态的sql生成.此解决方案已修复,前提是您可以为希望一次比较的最大产品添加足够的连接.我相信它不会超过5.
= 1,= 2和= 3应该用参数代替.查询应托管在存储过程中.
; with transponded as
(
select ID, Type, Value
from
(
select ID,
Name,
cast (Cost as varchar(100)) Cost,
cast (case when Included = 1 then 'Yes' else 'No' end as varchar(100)) Included
from ProductInfo
) p
unpivot (Value for Type in (Name, Cost, Included) ) a
)
select t1.Type,
t1.Value Product1,
t2.Value Product2,
t3.Value Product3
from transponded t1
left join transponded t2
on t1.Type = t2.Type
and t2.id = 2
left join transponded t3
on t1.Type = t3.Type
and t3.id = 3
where t1.id = 1
Run Code Online (Sandbox Code Playgroud)
简而言之,在时间上转发一条记录并按类型列加入另一条转发记录.
| 归档时间: |
|
| 查看次数: |
175 次 |
| 最近记录: |