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
440 views
in Technique[技术] by (71.8m points)

sql - How to retrieve same column twice with different conditions in same table?

This is my table:

Anganbadi_ID               Food     Month
-------------------------------------------    
1165                       ???         1
1165                       ???         2
1165                       ???         4
1168                       ???         4
2032                       ????        4
2218                       ????        4
2219                       ???         4
2358                       ????        4
2546                        ???        10 

there are 4 columns Anganbadi_ID, Food, Month, Year and I want to compare Food column twice based on two different month values.

e.g. if I select Month=4 for first Food (Food-1) column and Month=10 for second Food (Food-2) column, then it should be like following::

Anganbadi_ID            Food-1     Food-2    
------------------------------------------    
1165                       ???          NULL 
1168                       ???          NULL 
2032                       ????        NULL 
2218                       ????        NULL 
2219                       ???          NULL 
2358                       ????        NULL 
2546                     NULL        ??? 

When I'm trying this code

SELECT     
   Anganbadi_ID, Food,
   (SELECT Food
    FROM Anganbadi AS Anganbadi_2
    WHERE (Anganbadi_1.Anganbadi_ID = Anganbadi_ID) 
      AND (Anganbadi_1.Month = 10)
   ) AS 'Food(2)'
FROM Anganbadi AS Anganbadi_1
WHERE (Month = 4)

It shows following results::

Anganbadi_ID              Food-1     Food-2    
--------------------------------------------
1165                       ???          NULL 
1168                       ???          NULL 
2032                       ????        NULL 
2218                       ????        NULL 
2219                       ???          NULL 
2358                       ????        NULL 

Please help me as soon as possible....

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
SELECT DISTINCT Anganbadi_ID,

(SELECT Food 
 FROM Anganbadi 
 WHERE      (Anganbadi_ID = A.Anganbadi_ID) 
    AND (Month = 4)) AS Food1,

(SELECT Food 
 FROM Anganbadi 
 WHERE      (Anganbadi_ID = A.Anganbadi_ID) 
    AND (Month = 10)) AS Food2

FROM Anganbadi AS A 
WHERE A.Month = 10 OR A.Month = 4

SQL Fiddle


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

...