简体   繁体   English

SQL Server 2000中的交叉表查询

[英]Crosstab Query in SQL Server 2000

I am hoping that someone has attempted this before and I can get some advice before I go any further. 我希望以前有人试过这个,我可以先得到一些建议。

I am looking to produce something similar to a crosstab query in sql-server 2000. 我希望在sql-server 2000中生成类似于交叉表查询的东西。

I have a table structure similar to the following: 我有一个类似于以下的表结构:

Item       Item_Parameter      Parameter
id         item_id             id
desc       parameter_id        desc
           value

What I am looking to do is to flatten out the data through a query/stored procedure to make building reports easier. 我要做的是通过查询/存储过程来展平数据,以使构建报告更容易。

The ideal solution would produce results such as: 理想的解决方案将产生如下结果:

             Parameter.desc[0]      Parameter.desc[1]      Parameter.desc[3]...
item.id[0]   Item_Parameter.value   Item_Parameter.value   Item_Parameter.value
item.id[1]   Item_Parameter.value   Item_Parameter.value   Item_Parameter.value   

If you're sure there's at most one value for each parameter-item combination, you can use a simple group by : 如果您确定每个参数项组合最多只有一个值,则可以使用一个简单的group by

select  item_id
,       max(case when parameter_id = 1 then value) Par1
,       max(case when parameter_id = 2 then value) Par2
,       max(case when parameter_id = 3 then value) Par3
from    item_paramenter
group by
        item_id

You can use min or avg instead of max : it shoulnd't matter because there's only one value for each parameter per item_id, 您可以使用minavg而不是max :它无关紧要,因为每个item_id的每个参数只有一个值,

Without dynamic SQL, there is no way to return column names based on the description in the parameter table. 如果没有动态SQL,则无法根据参数表中的描述返回列名。

I ended up using a stored procedure ( http://www.sqlteam.com/article/dynamic-cross-tabs-pivot-tables ) to create a sql statement dynamically. 我最终使用存储过程( http://www.sqlteam.com/article/dynamic-cross-tabs-pivot-tables )动态创建一个sql语句。

Thanks Dan and Andomar 谢谢Dan和Andomar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM