-1

我有 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”时它不起作用

我能做些什么?是摆脱额外重复记录的更好解决方案吗?

4

1 回答 1

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
于 2013-10-22T11:30:31.500 回答