mysql自我加入

时间:2012-03-08 02:50:08

标签: mysql inner-join

我有一个名为receive with 4 column的表:

id, date, volume, volume_units

音量单位始终存储为“Lbs”或“Gals”的值。

我正在尝试编写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" 

当我单独运行这些查询时,结果就会消失。我知道连接在这里是错误的,但我不知道我做错了什么来解决它。

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:0)

这是一个交叉连接,在加入时没有明显的条件,我不认为你的意思

如果你想总计你不需要加入的数量,只需像zerkms那样进行分组

答案 4 :(得分: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