0

我正在尝试创建一个数据透视表来转换值范围。我正在使用这个求和技巧,但我最近了解了数据透视运算符,并且我正在尝试将数据转换为数据透视表,因为这样代码可能更易于维护。(我重命名了我的表以使数据有点模糊)

        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
4

1 回答 1

1

如果您想将其转换为PIVOT,那么我的建议是创建一个表,其中包含您要确定id的每个 的: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

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

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

使用该表的好处是,如果您需要更多current_status_id的 ',那么您只需将其添加到表中,它们就会被计算在内,而无需更改您的查询。

于 2012-11-09T20:55:58.827 回答