2012-03-08 86 views
0

我有一个表调用4列接收:MySQL的自联接

id, date, volume, volume_units 

的体积单位始终是作为要么“磅”的值或“加尔斯”存储。

我正在尝试编写SQL查询以获取特定日期范围内Lbs和Gals中的卷的总和。沿着线的东西:(不工作)

SELECT sum(p1.volume) as lbs, 
p1.volume_units, 
sum(p2.volume) as gals, 
p2.volume_units 
FROM receiving as p1, receiving as p2 
where p1.volume_units = 'Lbs' 
and p2.volume_units = 'Gals' 
and p1.date between "2012-01-01" and "2012-03-07" 
and p2.date between "2012-01-01" and "2012-03-07" 

当我运行这些查询单独的结果是路要走。我知道这里的连接是错误的,但我不知道我在做什么错误来修复它。

+0

你有一个巨大的'交叉join'发生这是什么原因造成您的问题。你需要指定你正在'加入''开'以使其变得准确。 – judda 2012-03-08 06:10:44

回答

1

您可以通过SUM内使用IF(condition,then,else)在一个查询实现这一目标:

SELECT SUM(IF(volume_units="Lbs",volume,0)) as lbs, 
     SUM(IF(volume_units="Gals",volume,0)) as gals, 
FROM receiving 
WHERE `date` between "2012-01-01" and "2012-03-07" 

这只会增加volume,如果它是正确的单位。

+0

这正是我在找的,谢谢。我从来没有在SQL中使用过条件语句,很显然,我需要一个连接。感谢所有回答如此迅速并且答案很好的人! – user1256132 2012-03-08 03:59:42

5
SELECT SUM(volume) AS total_sum, 
     volume_units 
    FROM receiving 
    WHERE `date` BETWEEN '2012-01-01' 
        AND '2012-03-07' 
GROUP BY volume_units 
0

这是对连接没有可见的条件的交叉连接,我不认为你意味着

如果要总结的数量,你并不需要在所有的加盟,只是组作为zerkms

1

该查询将显示每个ID的总计。

SELECT s.`id`, 
     CONCAT(s.TotalLbsVolume, ' ', 'lbs') as TotalLBS, 
     CONCAT(s.TotalGalVolume, ' ', 'gals') as TotalGAL 
FROM 
    (
     SELECT `id`, SUM(`volume`) as TotalLbsVolume 
     FROM Receiving a INNER JOIN 
        (
         SELECT `id`, SUM(`volume`) as TotalGalVolume 
         FROM Receiving 
         WHERE (volume_units = 'Gals') AND 
           (`date` between '2012-01-01' and '2012-03-07') 
         GROUP BY `id` 
        ) b ON a.`id` = b.`id` 
     WHERE (volume_units = 'Lbs') AND 
       (`date` between '2012-01-01' and '2012-03-07') 
     GROUP BY `id` 
    ) s 
0

您可以简单地按日期和volume_units进行分组,而无需自加入。

SELECT date, volume_units, sum(volume) sum_vol 
FROM receving 
WHERE date between "2012-01-01" and "2012-03-07" 
GROUP BY date, volume_units 

样品测试:

select d, vol_units, sum(vol) sum_vol 
from 
(
select 1 id, '2012-03-07' d, 1 vol, 'lbs' vol_units 
union 
select 2 id, '2012-03-07' d, 2 vol, 'Gals' vol_units 
union 
select 3 id, '2012-03-08' d, 1 vol, 'lbs' vol_units 
union 
select 4 id, '2012-03-08' d, 2 vol, 'Gals' vol_units 
union 
select 5 id, '2012-03-07' d, 10 vol, 'lbs' vol_units 
) t 
group by d, vol_units