在连接中显示空值销售价值 - 类别

时间:2017-08-15 13:27:45

标签: mysql sql

SELECT
   cat_tbl.id_cat, 
   cat_tbl.name, 
   Sum(expences.price) AS PriceTotal
FROM cat_tbl
  JOIN  expences ON cat_tbl.id_kat= expences.category

GROUP BY
    cat_tbl.id_cat, 
    cat_tbl.name

结果

+------+--------------+--------+
| name | PriceTotal   | id_cat |
+------+--------------+--------+
| Cat1 |      1031.40 |      1 |
| Cat2 |       200.88 |      2 |
| Cat4 |        46.44 |      4 |
| Cat5 |       223.76 |      5 |
+------+--------------+--------+

事情是我有超过4个类别,我尝试使用不同的连接,但他们不会显示具有PriceTotal空值的1-7类别。

我真的不知道如何制作它

+------+--------------+--------+
| name | PriceTotal   | id_cat |
+------+--------------+--------+
| Cat1 |      1031.40 |      1 |
| Cat2 |       200.88 |      2 |
| Cat3 |         0    |      3 |
| Cat4 |        46.44 |      4 |
| Cat5 |       223.76 |      5 |
| Cat6 |       0      |      6 |
| Cat7 |       0      |      7 |
+------+--------------+--------+

2 个答案:

答案 0 :(得分:2)

左连接的2个选项:

SELECT
   cat_tbl.id_cat, 
   cat_tbl.name, 
   Sum(expences.price) AS PriceTotal
FROM cat_tbl
  LEFT JOIN  expences 
     ON cat_tbl.id_kat= expences.category
GROUP BY
    cat_tbl.id_cat, 
    cat_tbl.name

或:

select cat.id_cat, cat.name,
       coalesce(exp.tot, 0) as PriceTotal
from cat_tbl cat
left join
(
select x.category, sum(x.price) as tot
from expences x
group by x.category
) exp
on cat.id_cat = exp.category

答案 1 :(得分:0)

   SELECT ct.id_cat, ct.name, Sum(ex.price) AS PriceTotal
   FROM cat_tbl ct
   JOIN  expences ex ON ct.id_cat= ex.category
   LEFT JOIN expences ex2 ON (ct.id_cat = ex2.category AND ex.category < ex2.category)
   .....
   WHERE ex2.category IS NULL