基于列值拆分数据的SQL查询
我有以下数据:基于列值拆分数据的SQL查询,sql,sql-server,excel,Sql,Sql Server,Excel,我有以下数据: 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
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中的值和优先级在不同的列中返回最后一列(TTRespond)中的数据
我想返回如下数据:
Priority P1 - Urgent P1 - Urgent P1 - Urgent P1 - Urgent P1 - Urgent P1 - Urgent
----------- ----------- ----------- ----------- ----------- ----------- -----------
Week # 31 32 33 34 35 36
我不想总结数据(如计数平均值等),我只想返回符合这两个标准的所有行。我在Excel中使用基于数组的公式获得了结果,但速度非常慢,无法处理源记录集(只有25000行)
任何帮助都将不胜感激
谢谢你问什么还不完全清楚。但是,假设您正在查找这样的输出,其中优先级/周数是列,所有可能的匹配值都列在行中:
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
可以通过添加更多按照上述示例建模的列组合来扩展可能的值。欢迎使用Stackoverflow!看起来你有一个很好的问题在酝酿。。。然而,我认为你需要更详细地说明预期的行为是什么(“紧急周”是什么意思??)。例如,您可能会以与起始数据类似的形式创建所需的输出?您提到
在最后一列中返回数据(TTRespond)
,但在要返回的数据中,您没有提到TTRespond
。有什么理由你不展示吗?你能解释一下吗?不过我在读你的问题,我不明白你想要什么。一方面,它听起来像你只想要一个WHERE子句,比如“WHERE OPEN_WEEK=@openWeekParam AND PRIORITY=@priorityParam”,另一方面,它听起来像你只想要“groupby OPEN_WEEK,PRIORITY”。所以请再解释一下你想要什么。您提到需要TTResponse,但在您的响应示例中,TTResponse不存在。您在TTResponse
列中缺少一些值,这些值的默认值是什么?