Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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....

like image 413
chitrakant sahu Avatar asked May 07 '13 16:05

chitrakant sahu


1 Answers

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

like image 86
Nalaka526 Avatar answered Oct 27 '22 00:10

Nalaka526