代码之家  ›  专栏  ›  技术社区  ›  Eduardo Rascon

如何在主表中每个记录只能得到一行?

  •  1
  • Eduardo Rascon  · 技术社区  · 14 年前

    我有三张桌子:

    苹果

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

    FARM          | RED | YELLOW | GREEN
    -------------------------------------
    GEORGE'S FARM | YES |  YES   |  YES
    JOHN's FARM   | YES |  NO    |  YES
    
    2 回复  |  直到 14 年前
        1
  •  2
  •   OMG Ponies    14 年前

    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
    
        2
  •  0
  •   Bill Karwin    14 年前
    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;