在多表查询中,每条记录只能获得一行吗?
我有这三张桌子:
ID | APPLE
----------
1 | RED
2 | YELLOW
3 | GREEN
ID | FARM
--------------------
B1 | GEORGE'S FARM
B2 | JOHN'S FARM
FARM | APPLE
---------------
B1 | 1
B1 | 2
B1 | 3
B2 | 1
B3 | 3
使用这个表我需要这个结果:
FARM_NAME | APPLE_1 | APPLE_2 | APPLE_3
----------------------------------------
B1 | 1 | 2 | 3
B2 |1 | | 3
非常感谢任何帮助,提前谢谢。
修改
感谢OMG小马和比尔,我会尝试你的两个解决方案,最后一件事,它可以得到这个结果:
FARM | RED | YELLOW | GREEN
-------------------------------------
GEORGE'S FARM | YES | YES | YES
JOHN's FARM | YES | NO | YES
答案 0 :(得分:2)
Firebird 2.0 supports the CASE expression,您可以使用:
SELECT fa.farm AS farm_name,
MAX(CASE WHEN fa.apple = 1 THEN fa.apple ELSE NULL END AS apple_1,
MAX(CASE WHEN fa.apple = 2 THEN fa.apple ELSE NULL END AS apple_2,
MAX(CASE WHEN fa.apple = 3 THEN fa.apple ELSE NULL END AS apple_3,
FROM FARM_APPLES fa
GROUP BY fa.farm
答案 1 :(得分:0)
SELECT F.ID AS FARM_NAME,
A1.APPLE AS APPLE_1,
A2.APPLE AS APPLE_2,
A3.APPLE AS APPLE_3
FROM FARMS AS F
LEFT OUTER JOIN FARM_APPLES AS A1 ON F.ID = A1.FARM AND A1.APPLE = 1
LEFT OUTER JOIN FARM_APPLES AS A2 ON F.ID = A2.FARM AND A2.APPLE = 2
LEFT OUTER JOIN FARM_APPLES AS A3 ON F.ID = A3.FARM AND A3.APPLE = 3;