从多列查询中选择不同的行

时间:2016-05-05 21:37:26

标签: sql-server

我有这个查询当前返回我需要的所有相关信息,但我需要它只返回唯一的DISPLAYCLAIMNUMBER行。我试过在它之前抛出一个DISTINCT,但是这给了我一个无效语法的错误。我对如何将DISTINCT置于SELECT中间的某些内容感到困惑。我的查询顺序也很重要,因为我将数据发送到Excel表格。我确定这是一个非常低效的,但是数据库非常分散,我必须引用几个表,仅用于一个数据。如果有办法,请随意改进。

SELECT cd.NAMECREFID, clm.CONTACTNAME, cd.ASSIGNEDPOLICY, clm.DISPLAYCLAIMNUMBER, clm.CAUSEOFLOSS, scp.PERILCODE, scp.DESCRIBE, clm.ASSIGNEDDATETIME, clm.CLOSEDATETIME, clp.PAYMENT
FROM CLMSTAT clm
inner join SCPERTBL scp on clm.ASSIGNEDPERILNUMBER = scp.PERILCODE
inner join CLMPYMT clp on clm.ASSIGNEDCLAIMNUMBER = clp.ASSIGNEDCLAIMNUMBER 
inner join SNAMES sn on clm.CONTACTNAME = sn.NAME
inner join TCUSDTL cd on sn.NAMEID = cd.NAMEID
WHERE clm.CONTACTNAME Like '%Smith%'
ORDER BY clm.CONTACTNAME, clm.ASSIGNEDDATETIME DESC

2 个答案:

答案 0 :(得分:2)

你应该试试这个

SELECT 
DISTINCT -- at the start
cd.NAMECREFID, clm.CONTACTNAME, cd.ASSIGNEDPOLICY, clm.DISPLAYCLAIMNUMBER, clm.CAUSEOFLOSS, scp.PERILCODE, scp.DESCRIBE, clm.ASSIGNEDDATETIME, clm.CLOSEDATETIME, clp.PAYMENT
FROM CLMSTAT clm
inner join SCPERTBL scp on clm.ASSIGNEDPERILNUMBER = scp.PERILCODE
inner join CLMPYMT clp on clm.ASSIGNEDCLAIMNUMBER = clp.ASSIGNEDCLAIMNUMBER 
inner join SNAMES sn on clm.CONTACTNAME = sn.NAME
inner join TCUSDTL cd on sn.NAMEID = cd.NAMEID
WHERE clm.CONTACTNAME Like '%Smith%'
ORDER BY clm.CONTACTNAME, clm.ASSIGNEDDATETIME DESC

这将为您提供SELECT列表中所有列的唯一组合。

但是,如果这不是你想要的,而你只想要clm.DISPLAYCLAIMNUMBER的唯一值,我会问为什么你需要休息?如果不这样,那么您的查询的SELECT列表应该如下所示

SELECT DISTINCT clm.DISPLAYCLAIMNUMBER
FROM CLMSTAT clm 
...

答案 1 :(得分:0)

SELECT cd.NAMECREFID, clm.CONTACTNAME, cd.ASSIGNEDPOLICY, clm.DISPLAYCLAIMNUMBER, clm.CAUSEOFLOSS, scp.PERILCODE, scp.DESCRIBE, clm.ASSIGNEDDATETIME, clm.CLOSEDATETIME, clp.PAYMENT
FROM CLMSTAT clm
inner join SCPERTBL scp on clm.ASSIGNEDPERILNUMBER = scp.PERILCODE
inner join CLMPYMT clp on clm.ASSIGNEDCLAIMNUMBER = clp.ASSIGNEDCLAIMNUMBER 
inner join SNAMES sn on clm.CONTACTNAME = sn.NAME
inner join TCUSDTL cd on sn.NAMEID = cd.NAMEID
WHERE clm.CONTACTNAME Like '%Smith%'
GROUP BY clm.DISPLAYCLAIMNUMBER
ORDER BY clm.CONTACTNAME, clm.ASSIGNEDDATETIME DESC