2017-04-10 51 views
0

我有一個表,其中每個客戶可以提交多次請求,但只有最新的請求將被受理。獨特的和最新提交

例如,customer1表可以只提出了1個請求和CustomerX可能提交了10個請求。所以當我拉取報告時,它會帶來customer1的1請求和CustomerX的第10個請求。

我該怎麼做?

客戶ID,FoodSelection1,FoodSelection2,DateSubmitted

+2

你會使用ROW_NUMBER。 https://docs.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql –

+0

你嘗試過什麼到目前爲止? – lukkea

回答

1

您可以使用在演唱會WITH TIES子句ROW_NUMBER()

Select Top 1 with ties * 
From YourTable 
Order By Row_Number() over (Partition By CustomerID Order by DateSubmitted Desc) 
0
SELECT m.CustomerId, m.FoodSelection1, m.FoodSelection2, m.DateSubmitted FROM tblpm m 
    WHERE m.DateSubmitted =(SELECT max(n.DateSubmitted) FROM tblpm n 
         where n.CustomerId=m.CustomerIdORDER) 
+1

LIMIT 1不是sql server語法。 – scsimon

+0

我更新它刪除限制並增加客戶ID控制 – coenni

0
select * from MyTable T1 
where not exists --exclude records where 
(
select 1 from MyTable T2 
where T1.[Customer Id]=T2.[Customer Id] --there is matching rcd for customer 
and T1.DateSubmitted<T2.DateSubmitted --a newer one exists 
) 
+0

您想在[客戶ID]和DateSubmitted指數以這種高效運行。 – jerry

0
select 
    t.Customer, 
    t.id, 
    t.FoodSelection1, 
    t.FoodSelection2, 
    t.DateSubmitted 
from MyTable T1 as t 
where t.datesubmited in 
    (select max(r.datesubmited) 
     from table 1 as r 
     where t.idCustomer = r.idCustomer 
     group by r.idcustomer)