2017-06-17 101 views
0

加入和組比方說,我有如下表:來自同一個表合併兩個查詢使用左邊

brand | model | country | sales | year | month 
--------|---------|----------|-------|--------|------- 
brand1 | model1 | US  | 10 | 2017 | 5 
brand1 | model2 | US  | 11 | 2017 | 5 
brand2 | model1 | US  | 5  | 2017 | 5 
brand2 | model2 | US  | 18 | 2017 | 5 
brand3 | model1 | US  | 8  | 2017 | 5 
brand3 | model2 | US  | 12 | 2017 | 5 
brand1 | model1 | US  | 80 | 2016 | 5 
brand1 | model2 | US  | 21 | 2016 | 5 
brand2 | model1 | US  | 35 | 2016 | 5 
brand2 | model2 | US  | 25 | 2016 | 5 
brand3 | model1 | US  | 5  | 2016 | 5 
brand3 | model2 | US  | 2  | 2016 | 5 
brand1 | model1 | DE  | 5  | 2017 | 5 
brand1 | model1 | DE  | 5  | 2017 | 4 
brand3 | model2 | P  | 2  | 2016 | 5 

我想顯示每個品牌在下降的銷售總額在某一特定國家(美國)訂購特定年份(2017)的特定月份(5)。這是我寫的查詢:

$country = str_replace ('-', '[- ]', $_GET['country']); 
$year = $_GET['year']; 
$month = $_GET['month']; 
$previousyear = $year - 1; 

$sql = "SELECT brand, SUM(sales) as sumsales 
FROM `exampletable` 
WHERE country REGEXP :country AND year = :year AND month = :month 
GROUP BY brand ORDER BY sumsales DESC"; 

$stmt = $pdo->prepare($sql); 
$stmt->bindParam(":country", $country); 
$stmt->bindParam(":year", $year); 
$stmt->bindParam(":month", $month); 
$stmt->execute(); 
... 

然後,我認爲這將是不錯的另一列添加到顯示每個品牌的銷售數字在同一個國家同月(5)去年的結果(2016 )。我試圖做到這一點使用left join,但是你會發現我的知識來開發這些類型的查詢的只是不夠好...:

$sql = "SELECT a.brand, SUM(a.sales) as asumsales, SUM(b.sales) as bsumsales FROM exampletable a 
LEFT JOIN exampletable b on a.brand = b.brand 
WHERE a.country REGEXP :country AND b.country REGEXP :country AND a.year = :year AND b.year = :previousyear AND a.month = :month AND b.month = :month 
GROUP BY brand ORDER BY asumsales DESC"; 

預期的結果:

brand | sales US, 2017, 5 | sales US, 2016, 5 
--------|-------------------|------------------- 
brand2 | 23    | 60 
brand1 | 22    | 101 
brand3 | 20    | 7 

哪有我得到這個結果?任何幫助將非常感激。

回答

1

如果您使用條件聚集那麼您可以在一個單一的查詢做到這一點:

SELECT 
    brand, 
    SUM(CASE WHEN year = 2017 AND month 5 THEN sales ELSE 0 END) AS sumsales1, 
    SUM(CASE WHEN year = 2016 AND month 5 THEN sales ELSE 0 END) AS sumsales2 
FROM exampletable 
WHERE country = 'US' 
GROUP BY brand 

請注意,您可以連接在一起的兩個子查詢爲每個要兩個和的,但是這將是更難的方式做到這一點。

+0

謝謝!看起來我正在使這種方式太難... – Stan

1

使用條件聚合。在你的情況下,這看起來像:

SELECT brand, 
     SUM(CASE WHEN year = :year THEN sales ELSE 0 END) as sales_curr, 
     SUM(CASE WHEN year = :year - 1 THEN sales ELSE 0 END) as sales_prev 
FROM exampletable 
WHERE country REGEXP :country AND 
     year IN (:year, :year - 1) AND 
     month = :month 
GROUP BY brand 
ORDER BY sales_curr DESC; 
+0

感謝您的幫助!這確實是我正在尋找的答案,但是隨着蒂姆第一個想出這個解決方案,我接受了他的答案作爲正確答案。 – Stan

+0

@Stan。 。 。我非常尊重蒂姆,但我回答是因爲他的回答不使用參數。 –