按列对数据进行分组
我有一个名为 Col_values 的表,而 Col_ID 是Identity 字段的数据如下所示:
Val_ID Col_ID Value
76951792 3 Closed
76951791 3 Closed
76951790 25 Open
76951789 25 Closed
76951792 1 US
76951791 1 Canada
另一个名为 Et_Col 的表,数据如下所示:
Col_ID Col_Name D_ID
3 Status 1
25 Status 2
1 Country 1
我希望输出为:
Val_ID Status Country
76951792 Closed US
76951791 Closed Canada
76951790 Open Null
76951789 Closed Null
所以我编写了一个游标来获取输出,游标返回如下语句:
Select val_ID
,max(case when Col_ID = 3 then Value end) as Status
,max(case when Col_ID = 25 then Value end) as Status
,max(CASE WHEN Col_ID = 1 THEN VALUE END ) AS Country
From Col_values
Group by Val_ID
这给了我输出为:
Val_ID Status Status Country
76951792 Closed Null US
76951791 Closed Null Canada
76951789 Null Closed Null
76951790 Null Open Null
我怎样才能解决这个问题吗?
Possible Duplicate:
dynamic sql pivot in sql server
I have a table called Col_values and Col_ID is an Identity field the data looks like:
Val_ID Col_ID Value
76951792 3 Closed
76951791 3 Closed
76951790 25 Open
76951789 25 Closed
76951792 1 US
76951791 1 Canada
and another table called Et_Col and the data looks like:
Col_ID Col_Name D_ID
3 Status 1
25 Status 2
1 Country 1
I want the output as:
Val_ID Status Country
76951792 Closed US
76951791 Closed Canada
76951790 Open Null
76951789 Closed Null
So I wrote a cursor to get the output and the cursor returns the statement like:
Select val_ID
,max(case when Col_ID = 3 then Value end) as Status
,max(case when Col_ID = 25 then Value end) as Status
,max(CASE WHEN Col_ID = 1 THEN VALUE END ) AS Country
From Col_values
Group by Val_ID
this gives me output as:
Val_ID Status Status Country
76951792 Closed Null US
76951791 Closed Null Canada
76951789 Null Closed Null
76951790 Null Open Null
How can I fix This?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
应该可以更改光标,使其生成如下所示的 sql:
不同的是,您使用 col_name 而不是 col_id 在列之间进行拆分,因此双倍的列名将合并。
It should be possible to change your cursor so that it generates sql like this then:
The different is that you are using the col_name to split between columns instead of the col_id, so the doubled up column names will merge.
这就是您想要的输出。为什么你认为你需要对数据进行分组才能得到它?
That's what would yield your desired output. Why do you think you need to group data to get that??