對於未來的讀者,這裏使用兩個嵌套派生表的子查詢一個一般化ANSI-SQL語法查詢。
這個查詢應該是大多數關係數據庫管理系統(SQL服務器,MySQL和SQLite的,甲骨文和PostgreSQL,DB2),因爲它不使用CTE窗口功能(WITH
)或數據庫特有的功能,如SQL Server的Pivot()
兼容:
SELECT [Key], [Employee Name], [Age],
Max(FF) As [First Floor],
Max(BSMT) As [Basement],
Max(PRKLotA) As [Parking Lot A]
FROM (
SELECT dT.Key,
dT.[Employee Name],
dT.[Age],
CASE WHEN dT.Project = 'First Floor' THEN dT.Hours END As FF,
CASE WHEN dT.Project = 'Basement' THEN dT.Hours END As BSMT,
CASE WHEN dT.Project = 'Parking Lot A' THEN dT.Hours END As PRKLotA
FROM (
SELECT [Employees].Key,
[Employees.[Employee Name],
Employees.Age, Projects.Project,
[Project Hours].Hours
FROM [Project Hours]
INNER JOIN Employees ON [Project Hours].[Employees FK] = Employees.Key
INNER JOIN Projects ON [Project Hours].[Projects FK] = Projects.Key
) AS dT
) As dT2
GROUP BY [Key], [Employee Name], [Age]
輸出:
Key Employee Name Age First Floor Basement Parking Lot A
1 Tim 40 1000 3000
2 John 5 2000 4000 5000
請發表您的嘗試,如果可能的話,在創建[SQLFiddle(http://sqlfiddle.com/)或[Rextester(http://rextester.com/一個樣機運行代碼)來輕鬆支持你 –