2012-03-08 81 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