2015-10-15 63 views
3

我想獲得一些排序和保持在一起(不是真正的分組)工作。 在我的示例數據中,我希望將DealerID保存在一起,按照IsPrimaryDealer DESC排序,但顯示最近輸入的經銷商的組(經銷商可能是分組)。按最近排序但由另一個ID列保持一致

結果集2是最接近的,但格蘭特和他的兄弟應該按順序顯示爲前兩行。 (格蘭特應該是第1行,資助兄弟行2,因爲資助弟弟被最近添加的)

DECLARE @temp TABLE (
    DealerPK int not null IDENTITY(1,1), DealerID int, 
    IsPrimaryDealer bit, DealerName varchar(50), DateAdded datetime 
) 

INSERT INTO @temp VALUES 
(1, 1, 'Bob', GETDATE() - 7), 
(2, 1, 'Robert', GETDATE() - 7), 
(3, 1, 'Grant', GETDATE() - 7), 
(3, 0, 'Grants Brother', GETDATE() - 1), 
(2, 0, 'Roberts Nephew', GETDATE() - 2), 
(1, 0, 'Bobs Cousin', GETDATE() - 3) 

-- Data As Entered 
SELECT * FROM @temp 
-- Data Attempt at Row Numbering 
SELECT *, intPosition = 
    ROW_NUMBER() OVER (PARTITION BY IsPrimaryDealer ORDER BY DealerID, IsPrimaryDealer DESC) 
FROM @temp 
ORDER BY DateAdded DESC 
-- Data Attempt By DateAdded 
SELECT *, intPosition = 
    ROW_NUMBER() OVER (PARTITION BY DealerID ORDER BY DateAdded DESC) 
FROM @temp 
ORDER BY intPosition, DateAdded 

預期結果

PK DID IsPr Name   DateAdded 
3 3 1  Grant   2015-10-08 17:14:26.497 
4 3 0  Grants Brother 2015-10-14 17:14:26.497 
2 2 1  Robert   2015-10-08 17:14:26.497 
5 2 0  Roberts Nephew 2015-10-13 17:14:26.497 
1 1 1  Bob    2015-10-08 17:14:26.497 
6 1 0  Bobs Cousin  2015-10-12 17:14:26.497 
+1

你能發佈你的預期結果嗎? –

+0

嗯,很難做到這一點(在上面的評論中無視PK)。如果你可以運行在OP上面的溫度,應該是格蘭特,他的兄弟,羅伯特,他的侄子,然後是鮑勃和他的表弟 – AdamRoof

+0

請編輯你的問題,併發布預期結果。 –

回答

2

按照要求通過OP:

;WITH Cte AS(
    SELECT *, 
     mx = MAX(DateAdded) OVER(PARTITION BY DealerID) FROM @temp 
) 
SELECT * 
FROM Cte 
ORDER BY mx DESC, DealerID, IsPrimaryDealer DESC 
0
Hope i understood your question, 
This query results expected output : 

SELECT Row_number() 
       OVER (
        PARTITION BY DealerID 
        ORDER BY DealerPK)RN, 
       DealerPK, 
       DealerID, 
       IsPrimaryDealer, 
       DealerName, 
       DateAdded 
     FROM #temp 
     ORDER BY DealerID DESC 
+0

感謝您的嘗試,我看到您要前往的目標,但它不起作用,因爲如果我添加一條新記錄,例如Roberts Sister,DealerID 2,IsPrimaryDealer 0,則Roberts記錄組不會移動到第一個位置。費利克斯帕米坦在原作後評論上面。 – AdamRoof