2017-05-04 130 views
0

我在我的數據庫中有每種產品的不同類型的表格。我想根據該類型爲每個產品拉出最高的1條記錄。這是我當前的查詢:從查詢列表中查詢每個類型的SQL查詢最高1值?

SELECT 
    dh_type, 
    dh_product 
FROM myProducts 
WHERE dh_productid = '08-BLD4011603S0' 
    AND dh_type IN ('New','Old','Ref') 
ORDER BY dh_createDt DESC 

每種類型可以有多個產品已在不同日期創建。我想爲每種類型拉最高記錄(最新的基於創建日期)。一個新的,一箇舊的和一個參考。我想知道什麼是在SQL中最好和最有效的方法?當前查詢將爲每種類型提取多個記錄,而我只需要一個記錄。

+1

添加一些示例表格數據和預期結果 - 以及格式化文本。 – jarlh

回答

2

有多種方式可以通過使用窗口功能(如row_number())來獲得您想要的方式。 row_number函數允許你爲每一行使用一個分區創建一個唯一的數字,在你的情況下,分區是dh_type,然後通過你的dh_createDT命令創建數字。那麼最終的結果將是一個ROW_NUMBER = 1:

select dh_type, 
     dh_product 
from 
(
    SELECT 
     dh_type, 
     dh_product, 
     rn = row_number() over(partition by dh_type order by dh_createDT desc) 
    FROM myProducts 
    WHERE dh_productid = '08-BLD4011603S0' 
     AND dh_type IN ('New','Old','Ref') 
) d 
where rn = 1; 

另一種方式來獲得的結果將是使用子查詢得到max(dh_createDT)每個dh_typedh_product行,然後加入該回你表:

select 
    dh_type, 
    dh_product 
from myProducts p 
inner join 
(
    select 
    dh_type, 
    dh_product, 
    MaxDate = max(dh_createDT) 
    from myProducts 
    where h_productid = '08-BLD4011603S0' 
    and dh_type IN ('New','Old','Ref') 
    group by dh_type, dh_product 
) p1 
    on p.dh_type = p1.dh_type 
    and p.dh_product = p1.dh_product 
    and p.dh_createDT = p1.MaxDate 
where p.h_productid = '08-BLD4011603S0' 
    and p.dh_type IN ('New','Old','Ref') 
1

Ollie有一個非常好的答案。然而,如果性能問題,那麼下面可能會更快:

(SELECT TOP (1) dh_type, dh_product 
FROM myProducts 
WHERE dh_productid = '08-BLD4011603S0' AND dh_type = 'New' 
ORDER BY dh_createDt DESC 
) UNION ALL 
(SELECT TOP (1) dh_type, dh_product 
FROM myProducts 
WHERE dh_productid = '08-BLD4011603S0' AND dh_type = 'Old' 
ORDER BY dh_createDt DESC 
) UNION ALL 
(SELECT TOP (1) dh_type, dh_product 
FROM myProducts 
WHERE dh_productid = '08-BLD4011603S0' AND dh_type = 'Ref' 
ORDER BY dh_createDt DESC 
); 

出於性能考慮,你想對myProducts(dh_productid, dh_type, dh_createDt)的索引。您也可以通過dh_product以及索引完全覆蓋查詢。