【问题标题】:SQL select combine data from multiple rows into a single rowSQL select 将多行中的数据合并为一行
【发布时间】:2016-04-27 01:19:03
【问题描述】:

我有一张类似这样的表格:

ID    OLD      NEW      TIME
1       a       b       5
1       b       c       7
1       c       d       45
1       d       e       4
2       a       b       1
2       b       d       8
2       d       e       45
3       b       c       15
3       c       d       14

我想建立一个看起来像这样的报告(基本上对于每个 OLD 数据点获取 TIME 值):

ID    TimeForA    TimeForB  TimeForC    TimeForD    
1     5           7         45          4
2     1           8         NULL        45
3     NULL        15        14          NULL

我已经能够将所有数据放入正确的列中,但无法将每一行合并为每个 ID 的单行。我当前的查询看起来像这样(不,我还没有准备好每一列,仍然只是测试):

WITH CTE (id, ATime, BTime) 
AS 
(
    select T1.oid, T1.loggedFor, null, T1.time as Atime
    from Table1 T1
    where T1.OLD = 'a'
    union
    select T1.oid, T1.loggedFor, T1.time as BTime, null
    from Table1 T1
    where T1.old = 'b'  
)
select ID, ATime, BTime
from CTE
order by ID

任何帮助表示赞赏!

【问题讨论】:

  • 请标记正在使用的数据库。
  • 添加了 SQL server 2008 标签,我的错。

标签: sql sql-server-2008 report common-table-expression


【解决方案1】:

试试这个:

select id, 
    sum(if(old = 'a',time,null)) as time_for_a,
    sum(if(old = 'b',time,null)) as time_for_b,
    sum(if(old = 'c',time,null)) as time_for_c,
    sum(if(old = 'd',time,null)) as time_for_d
from test_tbl
group by id
order by id;

【讨论】:

  • 谢谢,这很有帮助!
猜你喜欢
  • 2018-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 2021-08-19
相关资源
最近更新 更多