从sql查询中删除数据表中的重复项

时间:2014-05-15 07:10:41

标签: c# sql vb.net

基本上我在sql中有这段代码

SELECT DISTINCT A.fDate FROM tblReport_Date A 
LEFT JOIN tblReport_Type B ON A.ID_ReportType = B.ID 
LEFT JOIN tblReceiver C ON A.ID_Receiver = C.ID 
LEFT JOIN tblClients D ON A.ID_Client = D.ID 
WHERE A.fDate BETWEEN '1/1/2013 12:00:00 AM' AND '6/1/2014 12:00:00 AM'
AND B.fType = 'HCC' AND C.Receiver = '<test@test.com>'
AND D.fClientName = 'Radford'

现在,它会返回

9/25/2013 8:00:00 AM
10/3/2013 12:00:00 PM
12/5/2013 10:00:00 AM
12/5/2013 12:00:00 AM 

我想要的是像

9/25/2013 8:00:00 AM
10/3/2013 12:00:00 PM
12/5/2013 10:00:00 AM

甚至更好

9/25/2013 12:00:00 AM
10/3/2013 12:00:00 AM
12/5/2013 12:00:00 AM

我知道在我当前的查询中这是不可能的,因为

12/5/2013 10:00:00 AM 12/5/2013 12:00:00 AM

具有不同的 TIME 值。这可以通过查询吗?

2 个答案:

答案 0 :(得分:2)

您可以按日期分组(没有时间),这应该适用于从2005年开始的大多数SQL-Server版本:

SELECT fDate = DATEADD(day, DATEDIFF(day, 0, A.fDate), 0) 
FROM tblReport_Date A 
LEFT JOIN tblReport_Type B ON A.ID_ReportType = B.ID 
LEFT JOIN tblReceiver C ON A.ID_Receiver = C.ID 
LEFT JOIN tblClients D ON A.ID_Client = D.ID 
WHERE A.fDate BETWEEN '1/1/2013 12:00:00 AM' AND '6/1/2014 12:00:00 AM'
AND B.fType = 'HCC' AND C.Receiver = '<test@test.com>'
AND D.fClientName = 'Radford'
GROUP BY DATEADD(day, DATEDIFF(day, 0, A.fDate), 0)

或者在SQL Server 2008之后,您将转换为Date

GROUP BY CAST(A.fDate AS DATE)

答案 1 :(得分:1)

;WITH CTE_Temp ( SELECT DISTINCT A.fDate FROM tblReport_Date A LEFT JOIN tblReport_Type B ON A.ID_ReportType = B.ID LEFT JOIN tblReceiver C ON A.ID_Receiver = C.ID LEFT JOIN tblClients D ON A.ID_Client = D.ID WHERE A.fDate BETWEEN '1/1/2013 12:00:00 AM' AND '6/1/2014 12:00:00 AM' AND B.fType = 'HCC' AND C.Receiver = '<test@test.com>' AND D.fClientName = 'Radford' ) SELECT DISTINCT DATE(fDate) FROM CTE_Temp