从同一个表的多行中选择列的值作为不同的列

时间:2013-05-27 18:22:09

标签: database

我有一个表具有以下定义:

CREATE TABLE [dbo].[Due] (
[dueID]           INT            IDENTITY (1, 1) NOT NULL,
[dueTypeID]       INT            NOT NULL,
[vehicleID]        INT            NOT NULL,
[dueDate]         DATE           NULL,
...

这里我想生成一个输出为

的查询
VehicleID  Type1.dueDate  Type2.dueDate  Type3.dueDate ... 

(截止日期应为该车型的最低日期)

我写了以下查询来执行此操作:

select vehicleNumber, A.dueDate, B.dueDate, C.dueDate, D.dueDate, E.dueDate, F.dueDate 
FROM Vehicle INNER JOIN 
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '1' GROUP BY Due.vehicleID) As A ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '2' GROUP BY Due.vehicleID) As B ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '3' GROUP BY Due.vehicleID) As C ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '4' GROUP BY Due.vehicleID) As D ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '5' GROUP BY Due.vehicleID) As E ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '6' GROUP BY Due.vehicleID) As F ON Vehicle.vehicleID = A.vehicleID
问题是,没有特定类型的到期日的车辆正在考虑其他车辆的价值。请帮我弄清楚如何解决这个问题,如果我这样做是正确的,或者是否有更好的方法来做到这一点?

(抱歉,如果问题重复,我尝试寻找它但找不到合适的关键字来搜索问题)

非常感谢帮助我。

1 个答案:

答案 0 :(得分:1)

试试这个:

 select vehicleNumber, 
     Max(case When dueTypeID = '1' Then dueDate Else null end) Typ1dueDate, 
     Max(case When dueTypeID = '2' Then dueDate Else null end) Typ2dueDate, 
     Max(case When dueTypeID = '3' Then dueDate Else null end) Typ3dueDate, 
     Max(case When dueTypeID = '4' Then dueDate Else null end) Typ4dueDate, 
     Max(case When dueTypeID = '5' Then dueDate Else null end) Typ5dueDate, 
     Max(case When dueTypeID = '6' Then dueDate Else null end) Typ6dueDate
 FROM Due d join Vehicle v 
     On v.vehicleId = d.vehicleId 
 Group By v.vehicleNumber