Microsoft SQL Server复制查询结果

时间:2014-09-30 21:18:20

标签: sql join duplicates

我有以下查询:

SELECT 
    ShipperName, S.ShipmentID, DepartureDate
FROM 
    SHIPMENT S, SHIPMENT_ITEM SI
WHERE 
    S.ShipmentID = SI.ShipmentID
    AND Value > 1000
ORDER BY 
    ShipperName ASC, DepartureDate DESC;

返回以下结果:

International                       4   2013-06-02
International                       4   2013-06-02
International                       4   2013-06-02
Worldwide                           3   2013-05-05

前三个结果相同,但我要找的是:

International                       4   2013-06-02
Worldwide                           3   2013-05-05

我做错了什么?

4 个答案:

答案 0 :(得分:0)

您可能需要在select语句中添加DISTINCT关键字。

像:

SELECT DISTINCT ShipperName, S.ShipmentID, DepartureDate
FROM SHIPMENT S, SHIPMENT_ITEM SI
WHERE S.ShipmentID = SI.ShipmentID
AND Value > 1000
ORDER BY ShipperName ASC, DepartureDate DESC; 

答案 1 :(得分:0)

;WITH CTE AS
(
    SELECT ShipperName
         , S.ShipmentID
         , DepartureDate
         , ROW_NUMBER() OVER (PARTITION BY ShipperName ORDER BY ShipperName) rn
    FROM SHIPMENT S 
    INNER JOIN SHIPMENT_ITEM SI
    ON S.ShipmentID = SI.ShipmentID
    WHERE Value > 1000
    ORDER BY ShipperName ASC, DepartureDate DESC
)
SELECT ShipperName
      ,ShipmentID
      ,DepartureDate
FROM CTE 
WHERE rn = 1

答案 2 :(得分:0)

使用EXPLICIT join,因为隐式JOIN已过时且已弃用

您似乎有多个条目与货件ID匹配,使用不同的关键字,或者您可能在某些列上缺少联接

SELECT distinct ShipperName, S.ShipmentID, DepartureDate
FROM SHIPMENT S
JOIN SHIPMENT_ITEM SI
ON S.ShipmentID = SI.ShipmentID
AND Value > 1000
ORDER BY ShipperName ASC, DepartureDate DESC;

答案 3 :(得分:0)

您选择的数据似乎完全来自货件表(ShipperNameS.ShipmentIDDepartureDate),但您要将该表加入ShipmentItem表,每件货物显然可能有多于一排。您的联接表每个项目都有一行(与发货表中的货件相关)。

显然,您只希望货件包含至少一个value大于1000的项目,但在编写查询时,您将获得每个项目的结果行< / em>有这样的价值。实现您想要的最简单方法可能就是将DISTINCT关键字添加到您的查询中,正如其他人所建议的那样。但是,还有其他选择,其中一些可能更适合不同的,更复杂的要求。