使用HSLQDB(2.2.9)我使用java JDBC連接的數據庫。在不使用JOIN的情況下在HSQLDB中樞軸
某甲已接種疫苗的1和3,某乙已收到2和4 使用這個簡單的查詢:
SELECT std.*,vac.Date FROM Students AS std
LEFT JOIN ValuesVaccination AS vac
ON vac.ID_Students = std.ID
我得到一個結果集,如:
ID | Name | ID_Vaccination | Date
1 | PersonA | 1 | 2011-06-01
1 | PersonA | 3 | 2012-03-21
1 | PersonB | 2 | 2012-08-11
2 | PersonB | 4 | 2012-09-08
我想要得到的是:
ID | Name | Vaccination1 | Vaccination2 | Vaccination3 | Vaccination4
1 | PersonA | 2011-06-01 | NULL | 2012-03-21 | NULL
2 | PersonB | NULL | 2012-08-11 | NULL | 2012-09-08
一種方法是:
SELECT std.*,
vac1.Date AS "Vaccination1",
vac2.Date AS "Vaccination2",
vac3.Date AS "Vaccination3",
vac4.Date AS "Vaccination4"
FROM Students AS std
LEFT JOIN ValuesVaccination AS vac1
ON vac1.ID_Students = std.ID AND vac1.ID_Vaccinations = 1
LEFT JOIN ValuesVaccination AS vac2
ON vac2.ID_Students = std.ID AND vac2.ID_Vaccinations = 2
LEFT JOIN ValuesVaccination AS vac3
ON vac3.ID_Students = std.ID AND vac3.ID_Vaccinations = 3
LEFT JOIN ValuesVaccination AS vac4
ON vac4.ID_Students = std.ID AND vac4.ID_Vaccinations = 4
問題是數不同的疫苗接種是可變。有沒有一種體面的方式來做到這一點,而不使用Java循環中的JOIN構建查詢?
我想通了PIVOT函數是我所需要的,但似乎HSQLDB不支持它並搜索stackoverflow和谷歌沒有提供有用的信息。
謝謝你的任何信息
如果有10種不同的疫苗接種會怎麼樣?還是30?它們可以由應用程序用戶創建和刪除 – user1952162
感謝您的回答,'MAX'函數正是我所需要的,因爲可以有多個值,我需要顯示最近的日期。 – user1952162
'PIVOT'也受到Oracle的支持。 –