1

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

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

问题是,对于特定类型没有到期日的车辆正在获取其他车辆的价值。请帮助我弄清楚如何解决这个问题,如果我以正确的方式这样做,或者是否有更好的方法来做到这一点?

(抱歉,如果我尝试查找问题但找不到正确的关键字来搜索问题,则该问题是重复的)

非常感谢你帮助我。

4

1 回答 1

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
于 2013-05-27T18:28:36.710 回答