一尘不染

如何在主表中每条记录仅获得一行?

sql

在多表查询中,每条记录只能获得一行?

我有这三个表:

苹果

ID | APPLE
----------
1  | RED
2  | YELLOW
3  | GREEN

疲劳风险管理系统

ID  | FARM
--------------------
B1  | GEORGE'S FARM
B2  | JOHN'S FARM

FARM_APPLES

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 Ponies和Bill,我将尽力尝试您的两种解决方案,这是最后一件事,它有可能获得以下结果:

FARM          | RED | YELLOW | GREEN
-------------------------------------
GEORGE'S FARM | YES |  YES   |  YES
JOHN's FARM   | YES |  NO    |  YES

阅读 158

收藏
2021-05-05

共1个答案

一尘不染

Firebird 2.0支持CASE表达式,因此您可以使用:

  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
2021-05-05