使用MySQL选择数据

时间:2018-12-28 12:12:53

标签: mysql sql

我在查询中要解决的挑战很小,我有以下查询:

SELECT SUM(total) AS total, products, DATE_FORMAT(TransDate, '%M') AS month
FROM orders
WHERE Status = 'paid'
AND YEAR(TransDate) = '2016'
GROUP BY Product, YEAR(TransDate), MONTH(TransDate)
ORDER BY TransDate ASC

我在此查询中得到的回报是:

<table border=1>
<tr>
  <th>total</th>
  <th>Product</th>
  <th>Month</th>
</tr>

<tr>
  <td>12000</td>
  <td>Ford Mondeo</td>
  <td>Jan</td>
</tr>
<tr>
  <td>23000</td>
  <td>Camaro</td>
  <td>Jan</td>
</tr>
<tr>
  <td>9000</td>
  <td>Golf</td>
  <td>Jan</td>
</tr>
<tr>
  <td>42000</td>
  <td>Audi A4</td>
  <td>Jan</td>
</tr>


<tr>
  <td>4566</td>
  <td>Ford Mondeo</td>
  <td>Feb</td>
</tr>
<tr>
  <td>35435</td>
  <td>Camaro</td>
  <td>Feb</td>
</tr>
<tr>
  <td>58456</td>
  <td>Golf</td>
  <td>Feb</td>
</tr>
<tr>
  <td>56465</td>
  <td>Audi A4</td>
  <td>Feb</td>
</tr>


<tr>
  <td>3522</td>
  <td>Ford Mondeo</td>
  <td>Mar</td>
</tr>
<tr>
  <td>468132</td>
  <td>Camaro</td>
  <td>Mar</td>
</tr>
<tr>
  <td>25225</td>
  <td>Golf</td>
  <td>Mar</td>
</tr>
<tr>
  <td>54612</td>
  <td>Audi A4</td>
  <td>Mar</td>
</tr>


<tr>
  <td>12000</td>
  <td>Ford Mondeo</td>
  <td>Apr</td>
</tr>
<tr>
  <td>23000</td>
  <td>Camaro</td>
  <td>Apr</td>
</tr>
<tr>
  <td>9000</td>
  <td>Golf</td>
  <td>Apr</td>
</tr>
<tr>
  <td>42000</td>
  <td>Audi A4</td>
  <td>Apr</td>
</tr>
<tr>
  <td>54554</td>
  <td>Beatle</td>
  <td>Apr</td>
</tr>

<tr>
  <td>12000</td>
  <td>Ford Mondeo</td>
  <td>May</td>
</tr>
<tr>
  <td>23000</td>
  <td>Camaro</td>
  <td>May</td>
</tr>
<tr>
  <td>9000</td>
  <td>Golf</td>
  <td>May</td>
</tr>
<tr>
  <td>42000</td>
  <td>Audi A4</td>
  <td>May</td>
</tr>
<tr>
  <td>54554</td>
  <td>Beatle</td>
  <td>May</td>
</tr>
</table>

在我的情况下,甲壳虫汽车在过去两个月中仅具有销售价值,而在前几个月中没有,我想知道在其他月份中是否有任何形式的销售价值出现, 0,在汽车实际销售的月份中,其全部价值是正确的。

非常感谢您的帮助

1 个答案:

答案 0 :(得分:2)

使用cross join生成所有产品/日期组合。然后使用left join输入订单信息。如果您没有其他便捷的方法(例如日历表),则可以使用orders上的子查询来获取日期:

SELECT ym.yyyymm, p.product, COALESCE(SUM(o.total), 0) AS total
FROM (SELECT DISTINCT DATE_FORMAT(TransDate, '%M') as yyyymm,
             YEAR(TransDate) as yyyy, MONTH(TransDate) as mm
      FROM orders o
      WHERE TransDate >= '2016-01-01' and TransDate < '2017-01-01'
     ) ym CROSS JOIN
     (SELECT DISTINCT o.product FROM orders o
     ) p LEFT JOIN
     orders o
     ON YEAR(o.TransDate) = ym.yyyy AND
        MONTH(o.TransDate) = ym.mm AND
        o.product = p.product AND
        o.Status = 'paid'
GROUP BY p.Product, ym.yyyymm
ORDER BY MIN(o.TransDate), p.Product;