加入和組比方說,我有如下表:來自同一個表合併兩個查詢使用左邊
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
哪有我得到這個結果?任何幫助將非常感激。
謝謝!看起來我正在使這種方式太難... – Stan