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
問題是,沒有特定類型的到期日的車輛正在採取其他車輛的價值。請幫我弄清楚如何解決這個問題,如果我這樣做是正確的,還是有更好的方法來解決這個問題?
(不好意思的情況下,這個問題是重複的,因爲我試圖尋找,但沒有找到合適的關鍵字搜索問題)
非常感謝幫助我。
哎,這個工作一點點加入到由於表。非常感謝! :)另外,我可以給類型表的列標題?如Max(case when whenTypeID ='1 Then ThenDate Else null end)As(從DueType中選擇DueType.dueTypeTitle,其中typeID ='1'), – nikhilthecoder
@nikhilthecoder。 。 。如果這有效,那麼你應該接受答案。 –