我有以下数据:
SR_ID OPEN_DATE OPEN_WEEK PRIORITY TTRespond
------- ----------- ----------- ----------- -------------
24720 01/10/2014 40 P2 - High 3.867066667
24437 11/09/2014 37 P2 - High 418.1992333
24007 04/08/2014 32 P1 - Urgent 12571.28308
24628 25/09/2014 39 P2 - High 3.0407
24446 12/09/2014 37 P2 - High 2694.122933
24420 10/09/2014 37 P3 - Normal
24479 15/09/2014 38 P2 - High 90.56748333
24924 15/10/2014 42 P3 - Normal 26.51546667
24706 01/10/2014 40 P2 - High
我正在尝试编写一个查询,该查询将根据OPEN_WEEK和PRIORITY中的值在单独的列中返回最后一列(TTRespond)中的数据。
我想像这样返回数据:
Priority P1 - Urgent P1 - Urgent P1 - Urgent P1 - Urgent P1 - Urgent P1 - Urgent
----------- ----------- ----------- ----------- ----------- ----------- -----------
Week # 31 32 33 34 35 36
我不想总结数据(即Count Average等),我只想返回符合这两个条件的所有行。我在Excel中使用基于数组的公式获得了结果,但它非常慢并且无法处理源记录集(仅25,000行)。
非常感谢任何帮助。
由于
答案 0 :(得分:1)
你并不完全清楚你在问什么。但是假设您正在寻找类似这样的输出,其中优先级/周数是列,并且所有可能的匹配值都列在行中:
P2 - High, Week 37 | P2 - High, Week 38 | P2 - High, Week 39 | P2 - High, Week 40
---------------------------------------------------------------------------------
418.1992333 | 90.56748333 | 3.0407 | 3.867066667
2694.122933 | | |
这种"行/列反转"被称为数据透视表。通过在SQL Server中以下列方式巧妙地使用group by
和max
子句,可以完成简单的数据透视表:
;with T as (
select
row_number() over (partition by priority, open_week order by open_date) ix
,T.*
from MyTable T
where TTrespond is not null
), R as (
select distinct ix from T
)
select
R.ix
,max(case when [OPEN_WEEK]=37 and T.ix=R.ix and [PRIORITY]='P2 - High' then TTRespond end) as [P2 - High, Week 37]
,max(case when [OPEN_WEEK]=38 and T.ix=R.ix and [PRIORITY]='P2 - High' then TTRespond end) as [P2 - High, Week 38]
,max(case when [OPEN_WEEK]=39 and T.ix=R.ix and [PRIORITY]='P2 - High' then TTRespond end) as [P2 - High, Week 39]
,max(case when [OPEN_WEEK]=40 and T.ix=R.ix and [PRIORITY]='P2 - High' then TTRespond end) as [P2 - High, Week 40]
from T, R
group by R.ix
可以通过添加在上述示例之后建模的更多列组合来扩展可能的值。