Query
查詢最佳匹配並排序
我正在嘗試按照以下方式編寫查詢:
select * from tbl where col1 = 1 and col2 = 2 and col3 = 3 order by ... ;
我首先想要所有 3 個
WHERE
條件匹配的所有結果(3/3),然後是任何 2 個條件匹配的所有結果(2/3),最後是任何 1 個條件匹配的結果(1/3)。這 3 個結果集中的每一個都需要按 排序
(col4, col5, col6)
。我可以在一個查詢中做到這一點嗎?
例如:
範例 http://img708.imageshack.us/img708/1646/sampletableresult1.jpg
創建測試數據的腳本:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MyTable]') AND type in (N'U')) DROP TABLE [dbo].[MyTable] GO CREATE TABLE dbo.MyTable ( col1 INT , col2 INT , col3 INT , col4 INT , col5 INT , col6 INT ) GO INSERT dbo.MyTable (col1, col2, col3, col4, col5, col6) SELECT 1,2,3,2,1,1 UNION ALL SELECT 1,2,30,1,1,1 UNION ALL SELECT 1,20,30,1,1,1 UNION ALL SELECT 10,20,3,1,1,1 UNION ALL SELECT 10,2,30,1,1,1 UNION ALL SELECT 10,2,3,1,1,1 UNION ALL SELECT 10,20,30,1,1,1 UNION ALL SELECT 1,2,3,1,1,1 UNION ALL SELECT 1,2,3,1,2,2 UNION ALL SELECT 1,2,3,1,2,3 UNION ALL SELECT 1,20,3,1,1,1 GO
SELECT col1, col2, col3, col4, col5, col6 FROM TableX WHERE col1 = 1 OR col2 = 2 OR col3 = 3 ORDER BY (CASE WHEN col1 = 1 THEN 1 ELSE 0 END) + (CASE WHEN col2 = 2 THEN 1 ELSE 0 END) + (CASE WHEN col3 = 3 THEN 1 ELSE 0 END) DESC, col4, col5, col6
或者,對於 MS-Access:
ORDER BY IIF(col1 = 1,1,0) + IIF(col2 = 2,1,0) + IIF(col3 = 3,1,0) DESC, col4, col5, col6
這會達到你想要的嗎?從技術上講,內聯視圖不是必需的,因為您可以按順序重複 case 語句。
select y.col1, y.col2, y.col3, y.col4, y.col5, y.col6 from ( select col1, col2, col3, case when col1 =1 and col2 = 2 and col3 = 3 then 1 when col1 = 1 and col2 = 2 and col3 <> 3 then 2 when col1 = 1 then 3 else 4 end x, col4, col5, col6 from table )y order by y.x, col4, col5, col6