SQL DISTINCT基于两个变量

时间:2013-11-30 18:31:51

标签: sql sybase

我正在尝试消除Customer_ID和Rule_Number都相同的重复值。任何想法如何实现?

由于

SELECT Violations_Temp.Temp_ID as 'ID', 
   Customers.Cust_Name as 'Homeowner', 
       Customers.Add1 as 'Unit', 
       Rules_Main.Rule_Number as 'Rule', 
        Violations_Temp.User_Name as 'Inspector', 
        DATE(Violations_Temp.Upload_TimeStamp) as 'Date', 
        Cast(Violations_Temp.Upload_TimeStamp as time) as 'Time'
        FROM Violations_Temp 
        JOIN Customers ON Customers.Customer_ID = Violations_Temp.Customer_ID 
        JOIN Rules_Main ON Rules_Main.Rules_ID = Violations_Temp.Violation_ID 

通过Loc回复消息 - 您可以从结果中看到(其中包括)房主Adam White有多条记录,其中规则为11 - 我需要设置此值,以便只为该组合返回一条记录< / p>

Screenshot http://hasoftware.ws/images/stackoverflow_002.jpg

2 个答案:

答案 0 :(得分:1)

希望此查询有效。我在这里使用了表别名:

SELECT C.*, T.Upload_TimeStamp, T.User_Name, X.Rule_Number
FROM Customers C,
     Violations_Temp T, 
     (SELECT
            T.Customer_ID,
            R.Rule_Number,
            MAX(T.Upload_TimeStamp) AS MAX_Upload_Timestamp 
      FROM 
        Violations_Temp T,
        Rules_Main R
      WHERE T.Violation_ID = R.Rules_ID
      GROUP BY C.Customer_ID, R.Rule_Number) X
WHERE
T.Customer_ID = C.Customer_ID
AND T.Customer_ID = X.Customer_ID
AND T.Upload_TimeStamp = X.MAX_Upload_Timestamp

答案 1 :(得分:0)

这可能不是最优雅的方式,但它可以工作......(当返回的数据加载到DataTable中时)......

Dim vHash As New Hashtable()
            Dim vDuplicate As New ArrayList()

            For Each Row As DataRow In PopupDT.Rows
                Dim vSearchString As String = Row("Homeowner") & "_" & Row("Rule")
                If vHash.Contains(vSearchString) Then

                    vDuplicate.Add(Row)
                Else
                    With vHash
                        .Add(vSearchString, String.Empty)
                    End With
                End If
            Next

            For Each Row As DataRow In vDuplicate
                PopupDT.Rows.Remove(Row)
            Next