SQL查询复杂化

时间:2015-05-26 16:00:36

标签: sql

您好我正在尝试应用此查询来查找我的数据库中的任何订单重复项。

Select order_info.id_num, order_info.order_id, order_info.cargo, order_info.weight, order_info.companyid_sending, order_info.companyid_receiving, order_info.from_city, order_info.destination_city, order_info.miles, order_info.time, order_info.fuel, order_info.damage, order_info.travel_cost, order_info.payment, order_info.first_name, order_info.date, order_info.truck_id_num
From order_info
Group By order_info.id_num
Having Count(order_info.id_num) > 1

问题是此查询仅显示副本中的一行而不是所有行。所以它只显示了这个:

e1005|o1001|tractors|13|c1003|c1002|Graz|Dijon|640|857|327|0|712|24229|ben|03/03/2015|t1001

而不是三个实例。

e1005|o1001|tractors|13|c1003|c1002|Graz|Dijon|640|857|327|0|712|24229|ben|03/03/2015|t1001
e1005|o1001|tractors|13|c1003|c1002|Graz|Dijon|640|857|327|0|712|24229|ben|03/03/2015|t1001
e1005|o1001|tractors|13|c1003|c1002|Graz|Dijon|640|857|327|0|712|24229|ben|03/03/2015|t1001

如何更改现有的SQL以提供上述结果而不是单行?

2 个答案:

答案 0 :(得分:2)

您可以将重复搜索用作子查询,并返回与id_num匹配的所有项目:

Select order_info.id_num, order_info.order_id, order_info.cargo, order_info.weight, order_info.companyid_sending, order_info.companyid_receiving, order_info.from_city, order_info.destination_city, order_info.miles, order_info.time, order_info.fuel, order_info.damage, order_info.travel_cost, order_info.payment, order_info.first_name, order_info.date, order_info.truck_id_num
From order_info
where id_num IN
(
    Select order_info.id_num
    From order_info
    Group By order_info.id_num
    Having Count(order_info.id_num) > 1
)

答案 1 :(得分:0)

SELECT order_info.id_num
    ,order_info.order_id
    ,order_info.cargo
    ,order_info.weight
    ,order_info.companyid_sending
    ,order_info.companyid_receiving
    ,order_info.from_city
    ,order_info.destination_city
    ,order_info.miles
    ,order_info.TIME
    ,order_info.fuel
    ,order_info.damage
    ,order_info.travel_cost
    ,order_info.payment
    ,order_info.first_name
    ,order_info.DATE
    ,order_info.truck_id_num
FROM order_info
INNER JOIN (
    SELECT order_info.id_num
    FROM order_info
    GROUP BY order_info.id_num
    HAVING Count(order_info.id_num) > 1
    ) order_info2 ON order_info.id_num = order_info2.id_num