带连接的select语句中的额外重复记录

时间:2013-10-22 11:24:46

标签: sql join subquery distinct

我有2个表,“read_barcodetolid”和“serial_barcode”。它们都有共同的ordernum字段。我想选择行而不想重复值, 起初我使用了这个查询:

SELECT  distinct(t1.ordernum)
                 , t1.tarikh,
                   t2.city,
                   t2.officeNum,
                   t2.provience
         FROM read_barcodetolid t1
         join serial_barcode t2 on t1.ordernum=t2.ordernum

只有ordernum字段才能正常工作。但是当我添加像城市这样的另一个字段时......它会产生一些重复的记录。

然后我写了这个:

SELECT DISTINCT (
        SELECT DISTINCT TOP (1) ordernum
        FROM read_barcodetolid
        WHERE (ordernum = seri.ordernum)
        ORDER BY ordernum DESC
        ) AS ordernum,
    (
        SELECT TOP (1) seri.officeNum
        FROM read_barcodetolid AS read_barcodetolid_2
        WHERE (ordernum = seri.ordernum)
        ORDER BY ordernum DESC
        ) AS officeNum,
    (
        SELECT TOP (1) provience
        FROM serial_barcode
        WHERE (ordernum = seri.ordernum)
        ) AS provience,
    (
        SELECT TOP (1) city
        FROM serial_barcode AS serial_barcode_1
        WHERE (ordernum = seri.ordernum)
        ) AS city,
    (
        SELECT TOP (1) tarikh
        FROM read_barcodetolid AS read_barcodetolid_1
        WHERE (ordernum = seri.ordernum)
        ) AS tarikh
FROM serial_barcode AS seri
WHERE (ordernum IS NOT NULL)
ORDER BY tarikh DESC

它返回结果但最后显示一些NULL记录,当我使用“where ordernum IS NOT NULL”时它不起作用

我该怎么办? 是摆脱额外重复记录的更好解决方案吗?

1 个答案:

答案 0 :(得分:0)

尝试使用group by子句

SELECT t1.ordernum, MAX(t1.tarikh) tarikh, MAX(t2.city) city, MAX(t2.officeNum) officeNum, MAX(t2.provience) provience
FROM read_barcodetolid t1 join serial_barcode t2 on t1.ordernum=t2.ordernum 
WHERE (ordernum IS NOT NULL)
GROUP BY t1.ordernum
ORDER BY MAX(t1.tarikh) DESC