SQL问题:如何将多个结果转换为单行?

时间:2009-11-02 16:05:51

标签: sql sql-server tsql pivot

我在数据库名称“火车延迟,列

”中有表格
train number(int),
DelayTime(int),
DelayReason(nchar)

因此列车可能因每个延迟原因而有多个延迟时间,例如:

trainnumber,Delaytime,DelayReason
1          ,5 sec    ,x
1          ,10 sec    ,Z
1          ,70 sec    ,TY

我想创建一个具有以下设计的水晶报告:

trainnumber, delaytime 1,delay reason 1 ,delaytime 2, delay reason 2,delaytime 3,delay reason 3

但我不知道哪个查询能让我得到这个结果。

我试过这个:

select delaytime from dbo.traindelay

但输出如下:

Delaytime
5
10
70

我不希望如此。我想要这样的东西:

delaytime1 ,delaytime2 ,delaytime3 

1 个答案:

答案 0 :(得分:0)

首先,我将通过添加一个名为Id的列来提出一个新结构,所以现在你有两个表:

  • Train(int Id,string Name)
  • TrainDelay(int Id,int TrainId,int DelayTime,nchar DelayReason

每条列车最多有3个延迟的SQL查询是:

select 
  t.Name, 
  d1.DelayTime   as Delay1, 
  d1.DelayReason as Reason1,
  d2.DelayTime   as Delay2, 
  d2.DelayReason as Reason2,
  d3.DelayTime   as Delay3, 
  d3.DelayReason as Reason3,
from Train as t
left join TrainDelay as d1 on d1.TrainId = t.Id 
left join TrainDelay as d2 on d2.TrainId = t.Id and d2.Id > d1.Id
left join TrainDelay as d3 on d3.TrainId = t.Id and d3.Id > d2.Id

请注意,如果同一列车的延误时间超过3次,那么每列火车的重复记录会有多个结果。你可以添加更多的连接,但如果你的桌子很大,它会变得非常慢。