MySQL查询多个表的计数

时间:2014-03-06 23:15:57

标签: mysql sql select

我在这里开始了一个SQL小提琴: http://sqlfiddle.com/#!2/26c26/7

您可以查看该示例表,并看到我在三个表中有多个车型。我正在尝试获得6列布局。前两列是JeepMart1模型,这些模型的数量,接下来的两列是JeepMart2模型,计数和最后两列是JeepMart3模型和计数。

来自小提琴表的查询结果如下:

Jeep1Models | Jeep1Counts | Jeep2Models | Jeep2Counts | Jeep3Models | Jeep3Counts |
Wrangler          3         Wrangler          1  
Grand Cherokee    2         Grand Cherokee    3         
                            Patriot           1         Patriot           5

想法是从每个JeepMart获取每个模型的计数。

如果可能的话,最重要的是获得每个模型的总数如下:(缩短了col名称的可读性)

Jeep1Mod | Jeep1Cou | Jeep2Mod | Jeep2Cou | Jeep3Mod | Jeep3Cou | Totals
Wrangler       3      Wrangler       1                               4
Grand Cher     2      Grand Cher     3                               5
                      Patriot        1      Patriot        5         6

我完全愿意以另一种方式查询这些数据,即使这意味着更改结果的布局,只要所有结果都存在,并且同样易于使用。

1 个答案:

答案 0 :(得分:1)

你想要COUNT(DISTINCT vin),如下所示

SELECT J1.model as Jeep1Model,
       COUNT(DISTINCT J1.vin) as Jeep1Counts,
       J2.model as Jeep2Model,
       COUNT(DISTINCT J2.vin) as Jeep2Counts,
       J3.model as Jeep3Model,
       COUNT(DISTINCT J3.vin) as Jeep3Counts,
       COUNT(DISTINCT J1.vin)+
       COUNT(DISTINCT J2.vin)+
       COUNT(DISTINCT J3.vin) as Total
FROM
(SELECT DISTINCT model FROM JeepMart1
UNION SELECT DISTINCT model FROM JeepMart2
UNION SELECT DISTINCT model FROM JeepMart3)A
LEFT JOIN JeepMart1 J1 ON J1.model = A.model
LEFT JOIN JeepMart2 J2 ON J2.model = A.model
LEFT JOIN JeepMart3 J3 ON J3.model = A.model
GROUP BY A.model

sqlFiddle