如何使用不同的条件查询相同的列

时间:2013-07-01 10:36:12

标签: sql oracle join self-join

我有2张桌子sugar_distribution和farmer_dir。

sugar_distribution表包含season_cd,farmer_id和Tons_supplied列。 farmer_dir包含farmer_name和farmer_id。我需要的是

Farmer_id       Farmer_name    Tons@2006         Tons@2012

123              Ramesh G       145.215           548.125
321              Ravish         214.123           783.215

season_cd是年份字段。我想分析2006年和2012年提供的那些派对。我尝试了下面的查询但没有得到我想要的东西。

SELECT DISTINCT farmer_id,

(SELECT sum(tons)
 FROM sugar_distribution
 WHERE      (farmer_id = A.farmer_id) 
    AND (season_cd = 2)) AS T2006,

(SELECT sum(tons)
 FROM sugar_distribution
 WHERE      (farmer_id = A.farmer_id) 
    AND (season_cd = 8)) AS T2012

FROM sugar_distribution A 
WHERE A.season_cd = 2 OR A.season_cd = 8 order by to_number(farmer_id)

3 个答案:

答案 0 :(得分:0)

试试这个:

        SELECT farmer_id, MAX(t2006), MAX(t2012)
        FROM
        (
        SELECT farmer_id, sum(case when season_cd = 2 then tons else 0 end) t2006, SUM(case when season_cd = 8 then tons else 0 end) t2012
         FROM sugar_distribution
         WHERE      (farmer_id = A.farmer_id) 
            AND season_cd in (2,8)
           group by farmer_id, season_cd
         ) t

答案 1 :(得分:0)

你很亲密。

select a.farmer_id, a.farmer_name,
 (select sum(tons_supplied)
            from sugar_distribution b
            where b.farmer_id = a.farmer_id
            and b.season_cd = 2) as t2006,
 (select sum(tons_supplied)
            from sugar_distribution b
            where b.farmer_id = a.farmer_id
            and b.season_cd = 8) as t2012
from farmer_dir a;

示例小提琴here

答案 2 :(得分:0)

这是使用条件聚合的聚合查询:

SELECT fd.farmer_id, fd.farmer_name,
       sum(case when season_cd = 2 then tons else 0 end) as tons2006,
       sum(case when season_cd = 8 then tons else 0 end) as tons2012
from farmer_dir fd join
     sugar_distribution sd
     on fd.farmer_id = sd.farmer_id
group by fd.farmer_id, fd.farmer_name
having tons2006 > 0 and tons2012 > 0

最终having条款只是确保农民有两年的记录。