0

我有两张桌子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)
4

3 回答 3

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
于 2013-07-01T10:53:37.630 回答
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;

样品小提琴在这里

于 2013-07-01T11:14:03.403 回答
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条款只是确保农民拥有这两年的记录。

于 2013-07-01T11:14:53.113 回答