我如何计算重复的列?

时间:2015-04-17 16:59:00

标签: mysql

我做了3个表,问题是我正在尝试计算表格中板数值的次数,并将其与特定政策进行比较。

TABLES

|vehicles|             
  |id|  |plate|          
    1   VEH001
    2   VEH002
    3   VEH003
    4   VEH004
    5   VEH001
    6   VEH002

|policy_vehicles|
  |id|  |vehicle_id| |policy_id|
   1         1            1
   2         2            1
   3         3            1
   4         4            2
   5         6            3

|policies|
  |id|  |description|
   1     POL1
   2     POL2
   3     POL3

我想计算在“数据库”中重复版块名称时,在这种情况下,“VEH001”会在来自policy_id = 1的桌面车辆上重复一次。

例如policy_id = 1

Policy: POL1 
Has 3 policy_vehicles  
Has 3 plates ( VEH001, VEH002, VEH003)
VEH001 and VEH002 are repeated in the DB = 2 plates repeated

我试图将此结果显示为

REPEATED
  2

另一个示例计数在“DATABASE”上没有重复板名称时,在这种情况下,“VEH004”不会在来自policy_id = 2的表格车辆上重复

例如policy_id = 2

Policy: POL2 
Has 1 policy_vehicles  
Has 1 plates ( VEH002 )
VEH002 is repeated in the DB = 1 plate repeated

我试图将此结果显示为

REPEATED
  0

在“DATABASE”上重复版块名称的另一个示例计数在这种情况下,“VEH002”在来自policy_id = 3的桌面车辆上重复

例如policy_id = 3

Policy: POL3 
Has 1 policy_vehicles  
Has 1 plates ( VEH004 )
VEH004 is not repeated

我试图将此结果显示为

REPEATED
  1

我尝试了this live demo

Select count(*) FROM (
  SELECT count(*), v.plate
  FROM vehicles v
  LEFT JOIN policy_vehicles pv ON v.id = pv.vehicle_id
  and pv.policy_id = 2
 GROUP by v.plate 
HAVING count(*) > 1 ) A

请有人帮我这个吗?

2 个答案:

答案 0 :(得分:1)

你说,"我希望计算所有牌照的特定政策"和"我想计算在"数据库"在这种情况下" VEH001"和" VEH002"在桌面车辆上重复2次。"

我相信会给你你的追求。这是计数完成后施加的限制。在计数完成之前应用Where子句。

SELECT count(*), v.plate
FROM vehicles v
LEFT JOIN policy_vehicles pv ON v.id = pv.vehicle_id
and pv.policy_id = 1
GROUP by v.plate 
HAVING count(*) > 1 ;

将返回所有印版及其各自的重复计数。 现在听起来你想要那个洙......

Select count(*) FROM (
   SELECT count(*), v.plate
FROM vehicles v
LEFT JOIN policy_vehicles pv ON v.id = pv.vehicle_id
and pv.policy_id = 1
GROUP by v.plate 
HAVING count(*) > 1 ) A

答案 1 :(得分:0)

在开始任何聚合之前,我会首先获取所有有问题的行。您可以使用这样的内部联接来执行此操作:

SELECT p.description, pv.vehicle_id, v.plate
FROM policies p
JOIN policy_vehicles pv ON pv.policy_id = p.id
JOIN vehicles v ON v.id = pv.vehicle_id
WHERE p.id = 1;

为了看每个车牌重复多少次,我写了一个子查询,得到每个盘子的计数:

SELECT v.plate, COUNT(*) AS repeated
FROM vehicles v
GROUP BY v.plate;

然后,我将两者加在一起,看看每个重复值:

SELECT t1.description, t1.vehicle_id, t1.plate, t2.repeated
FROM(
  SELECT p.description, pv.vehicle_id, v.plate
  FROM policies p
  JOIN policy_vehicles pv ON pv.policy_id = p.id
  JOIN vehicles v ON v.id = pv.vehicle_id
  WHERE p.id = 1) t1
JOIN(
  SELECT v.plate, COUNT(*) AS repeated
  FROM vehicles v
  GROUP BY v.plate) t2 ON t2.plate = t1.plate;

以下是SQL Fiddle示例。