Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

sql - How can I get only one row per record in master table?

it is possible to get only one row per record in a multitable query?

I have this three tables:

APPLES

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

FARMS

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

FARM_APPLES

FARM  | APPLE
---------------
B1    | 1
B1    | 2
B1    | 3
B2    | 1
B3    | 3

With this tables I need this result:

FARM_NAME | APPLE_1 | APPLE_2 | APPLE_3
----------------------------------------
B1        | 1       | 2       | 3
B2        |1        |         | 3

Any help is much appreciated, thanks in advance.

EDIT

Thanks both OMG Ponies and Bill, I'll try both of your solutions, just one last thing, its possible to get this result:

FARM          | RED | YELLOW | GREEN
-------------------------------------
GEORGE'S FARM | YES |  YES   |  YES
JOHN's FARM   | YES |  NO    |  YES
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Firebird 2.0 supports the CASE expression, so you can use:

  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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...