繁体   English   中英

使用左联接和分组依据合并来自同一表的两个查询

[英]Combining two queries from the same table using left join and group by

假设我有下表:

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();
...

然后,我认为最好在结果中添加另一列,以显示去年(2016年)在同一国家(5)相同国家/地区的每个品牌的销售数字。 我尝试使用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

我怎么能得到这个结果? 任何帮助将非常感激。

如果使用条件聚合,则可以在单个查询中执行此操作:

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

请注意,您可以针对所需的两个总和中的每一个将两个子查询合并在一起,但这将是更困难的方法。

使用条件聚合。 您的情况如下所示:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM