旋转值为范围的列

时间:2012-11-09 20:05:53

标签: sql sql-server pivot

我正在尝试创建一个数据透视表来转换值范围。我正在使用这个总和技巧,但我最近了解了pivot运算符,我正在尝试将数据转换为数据透视表,因为代码可能更容易维护。 (我已将我的表重命名为稍微模糊了数据)

        select  consultation_id,
                sum(case when current_status_id in (3,4,5,9,10,16,17,18,24,25,26) then 1 else 0 end) [Phase1],
                sum(case when current_status_id in (4,9,10,16,17,18) then 1 else 0 end) [Phase2],
                sum(case when current_status_id in  (10,16,17,18) then 1 else 0 end) [Phase3],
                sum(case when current_status_id = 24 then 1 else 0 end) [Rejected],
                sum(case when current_status_id in (17,18) then 1 else 0 end) [Complete]    
        from subject with (NOLOCK,NOWAIT)
        where ACTIVE_IND = 1
        group by consultation_id

有人建议如何进行转换吗?

编辑: 基本上,我正在创建一个总共有多少科目进入我们的咨询阶段。这是为lucene索引构建的聚合,以便我们的用户可以搜索特定数据。 这是一个原始表格数据的示例,以及输出可能是什么样的::

select  consultation_id,
                sum(case when current_status_id in (3,4,5,9,10,16,17,18,24,25,26) then 1 else 0 end) [Phase1],
                sum(case when current_status_id in (4,9,10,16,17,18) then 1 else 0 end) [Phase2],
                sum(case when current_status_id in  (10,16,17,18) then 1 else 0 end) [Phase3],
                sum(case when current_status_id = 24 then 1 else 0 end) [Rejected],
                sum(case when current_status_id in (17,18) then 1 else 0 end) [Complete]    
        from (values(1588054,11928257,3,1),
                (1588054,11928256,10,1),
                (1588054,11928255,10,1),
                (1588054,11928254,4,1),
                (1588052,11928233,2,1),
                (1588052,11928232,3,0),
                (1588052,11928231,10,1),
                (1588052,11928230,18,1),
                (1588052,11928229,24,1),
                (1588052,11928228,24,1)) subject (consultation_id,subject_id,current_status_id,active_ind)
        where ACTIVE_IND = 1
        group by consultation_id

1 个答案:

答案 0 :(得分:1)

如果您想将此转换为PIVOT,那么我的建议是创建一个表格,其中包含您要尝试的每个id的{​​{1}}个确定:

Phases

然后,您create table phases ( id int, name varchar(10) ); JOIN表格subject添加到current_status_id的新表格中,这样您就可以PIVOT数据:

select s.consultation_id,
  p.name
from subject s
left join phases p
  on s.current_status_id = p.id
where s.ACTIVE_IND = 1

所以你的最终查询是:

select *
from 
(
  select s.consultation_id,
    p.name
  from subject s
  left join phases p
    on s.current_status_id = p.id
  where s.ACTIVE_IND = 1
) src
pivot
(
  count(name)
  for name in ([Phase1], [Phase2], [Phase3], [Rejected], [Complete])
) piv;

请参阅SQL Fiddle with Demo

结果与您现有的查询匹配:

| CONSULTATION_ID | PHASE1 | PHASE2 | PHASE3 | REJECTED | COMPLETE |
--------------------------------------------------------------------
|         1588052 |      4 |      2 |      2 |        2 |        1 |
|         1588054 |      4 |      3 |      2 |        0 |        0 |

使用该表的好处是,如果您需要更多current_status_id,那么您只需将其添加到表中即可计算,无需更改查询。