避免SQL语句中的重复行

时间:2017-12-05 14:54:46

标签: sql distinct sybase

很长一段时间潜伏在这里的第一次海报。

我的问题是,以下sql查询返回重复的行:

select
inv.i4201 as pmid,
inv.i4235 as calPlace,
inv.i4204 as device,
inv.i4203 as type,
inv.i4202 as manufacturer,
inv.i4206 as serialNumber,
cal.c2323 as condition,
inv.i4299 as availability,
inv.i4236 as dateRegistration,
max(cal.c2301) as dateCalibration,
inv.i4229 as interval,
max(cal.c2303) as dateExpiry,
inv.i4228 as intervallType,
loc.l2803 as costCenter,
inv.i4242 as location,
cust.k4601 as CustomerNumber,
cust.k4602 as CustomerName
from
    inventory inv
        join customers cust on inv.ktag = cust.ktag
        join calibration cal on inv.mtag = cal.mtag
        join location loc on inv.mtag = loc.mtag
where   CustomerName like  'xxx%' and device like 'yyy%'

group by
pmid,
calPlace,
device,
type,
manufacturer,
serialNumber,
condition,
availability,
dateRegistration,
interval,
intervallType,
costCenter,
location,
CustomerNumber,
CustomerName

order by pmid;

如何使用最新的dateCalibration和/或dateExpiry为每个pmid获取一行?

3 个答案:

答案 0 :(得分:0)

我认为您可能需要进一步调查。这里真正的问题是"为什么你会得到重复的行?"是否有重复的客户记录?如果是,请尝试使用DISTINCT关键字。由于您要加入表格,有些客户有多个位置吗?还是多个校准记录?如果是这样,您需要确定您想要哪些记录"在你的结果集中。你想要第一张唱片吗?还是最新纪录?或者是否有其他条件来确定您要显示的数据?

在回答这些问题之后,请使用一些汇总函数,例如MAXMINSUMCOUNT等。这实际上取决于您需要提取的数据。

答案 1 :(得分:0)

请试一试。

select
inv.i4201 as pmid,
max(cal.c2301) as dateCalibration,
from
    inventory inv
        join customers cust on inv.ktag = cust.ktag
        join calibration cal on inv.mtag = cal.mtag
        join location loc on inv.mtag = loc.mtag
where   CustomerName like  'xxx%' and device like 'yyy%'

group by
pmid
order by pmid;

答案 2 :(得分:0)

以下查询每个pmid只返回一条记录:

    select
inv.i4201 as pmid,
max(cal.c2301) as dateCalibration,
inv.i4204 as device,
cust.k4602 as CustomerName
from
    inventory inv
        join customers cust on inv.ktag = cust.ktag
        join calibration cal on inv.mtag = cal.mtag
        join location loc on inv.mtag = loc.mtag
where   CustomerName like  'xxx%' and device like 'yyy%'

group by
pmid,
device,
CustomerName
order by pmid;

与此同时,我通过将结果导出到单个Postgres表中并使用简单的max()聚合函数删除重复行来解决了这个问题。

感谢大家有时间阅读我的帖子。