计算两列类别的总和

时间:2013-09-18 13:40:11

标签: mysql sql

我有两张桌子:

1.  Table Master(Vehicle,Vehicle_Color) :

Vehicle      Vehicle_Color
---------------------------
Car          Black
Car          Yellow
Car          White   
Car          Orange
motorcyle    Black
motorcyle    Yellow
motorcyle    White
motorcyle    Orange

2.  Table Data(Name,Vehicle,Vehicle_Color)  :

Name    Vehicle     Vehicle_Color
-----------------------------------
 Ony    motorcycle  white
Galih   motorcycle  white
Zening  motorcycle  black
 Lia    motorcycle  yellow
 Tika   motorcycle  yellow
Fredy   car         black
Kenzy   car         white
Arka    car         white
Nugraha car         white

我想选择vehicle,vehicle_color并计算车辆数量和颜色

 query :

 select vehicle,vehicle_color,(.....) as number 
 from Master left join data on ....

这样的结果

Vehicle      Vehicle_Color    Number
--------------------------------------
Car          Black               1
Car          Yellow              0
Car          White               3
Car          Orange              0
motorcyle    Black               1
motorcyle    Yellow              2
motorcyle    White               2
motorcyle    Orange              0

是否有任何建议,创建查询? TQ ..

1 个答案:

答案 0 :(得分:2)

您需要使用vehiclevehicle_color使用LEFT JOIN来加入两个表格,以便表格master上的所有记录都会显示在结果列表中。

SELECT  a.vehicle,
        a.vehicle_color,
        COUNT(b.vehicle) Number
FROM    master a
        LEFT JOIN data b
            ON a.vehicle = b.vehicle AND
                a.vehicle_color = b.vehicle_color
GROUP   BY a.vehicle,
           a.vehicle_color