棘手的SQL查询(至少对我来说!)

时间:2013-07-19 03:30:09

标签: sql

我有这个问题:

SELECT  trackingno, COUNT(trackingno) AS NumberOfTimes 
FROM shippinginfo
GROUP BY trackingno HAVING (COUNT(trackingno)>1) 
ORDER BY NumberOfTimes DESC

它报告了

的内容
Trackingno  |  NumberofTimes
12345       |  2
23456       |  2
34567       |  3

有没有办法进行查询,以便显示其他列数据?

Trackingno  |  OrderId
12345       |  oid1
12345       |  oid2
23456       |  oid3
23456       |  oid4
34567       |  oid5
34567       |  oid6

基本上我在表中查找任何DUPLICATE跟踪号码(trackingno),然后报告跟踪号码和重复跟踪号码行的orderid(orderid),以便我可以联系具有重复跟踪号码的客户。 / p>

2 个答案:

答案 0 :(得分:2)

SELECT *
  FROM shippinginfo
 WHERE trackingno IN (

    SELECT trackingno
      FROM shippinginfo
  GROUP BY trackingno
    HAVING COUNT(*) > 1

)

因此,在内部查询中,您选择了所有重复的trackingno,然后在外部选择您需要的任何内容

答案 1 :(得分:1)

SELECT Trackingno,orderId 
FROM shippinginfo
WHERE Trackingno IN (
                      SELECT trackingno
                      FROM shippinginfo
                      GROUP BY trackingno
                      HAVING COUNT(*) > 1

                     )