编写此SQL查询的任何其他替代方法

时间:2014-12-03 21:51:52

标签: sql sql-server

我需要根据三个条件选择数据

  1. 从表中查找每条记录的最新日期(StorageDate列)
  2. 查看相同ID(ID列)的第一步中是否有多个日期条目(StorageDate列)
  3. 然后查看DuplicateID是否为= 2
  4. 因此,如果表格包含以下数据:

    ID   |StorageDate | DuplicateTypeID
    1    |2014-10-22  | 1
    1    |2014-10-22  | 2
    1    |2014-10-18  | 1
    2    |2014-10-12  | 1
    3    |2014-10-11  | 1
    4    |2014-09-02  | 1
    4    |2014-09-02  | 2
    

    然后我应该得到以下结果

    ID  
    1
    4
    

    我写过以下查询,但它确实很慢,我想知道是否有人有更好的方法来编写它。

    SELECT DISTINCT(TD.RecordID)
    FROM dbo.MyTable TD
    JOIN (
        SELECT T1.RecordID, T2.MaxDate,COUNT(*) AS RecordCount
        FROM MyTable T1 WITH (nolock) 
        JOIN (
        SELECT RecordID, MAX(StorageDate) AS MaxDate
                FROM MyTable WITH (nolock)
                GROUP BY RecordID)T2 
        ON T1.RecordID = T2.RecordID AND T1.StorageDate = T2.MaxDate
        GROUP BY T1.RecordID, T2.MaxDate
        HAVING COUNT(*) > 1
        )PT ON TD.RecordID = PT.RecordID AND TD.StorageDate = PT.MaxDate
        WHERE TD.DuplicateTypeID = 2
    

2 个答案:

答案 0 :(得分:0)

您可以使用分析函数rank,您可以尝试此查询吗?

Select recordId from
(
  select *, rank() over ( partition by recordId order by [StorageDate] desc) as rn 
  from mytable
) T
where rn =1
group by recordId
having count(*) >1
and sum( case when duplicatetypeid =2 then 1 else 0 end) >=1

答案 1 :(得分:0)

试试这个,看看性能如何:

;WITH
    tmp AS
    (
        SELECT      *,
                    RANK() OVER (PARTITION BY ID ORDER BY StorageDate DESC) AS StorageDateRank,
                    COUNT(ID) OVER (PARTITION BY ID, StorageDate) AS StorageDateCount
        FROM        MyTable
    )

SELECT DISTINCT ID
FROM tmp
WHERE StorageDateRank = 1   -- latest date for each ID
  AND StorageDateCount > 1  -- more than 1 entry for date
  AND DuplicateTypeID = 2   -- DuplicateTypeID = 2