2017-02-24 61 views
-1

如何選擇既是國家級別又是國家級別的候選人,我只想選擇查詢應忽略較低級別的較高級別(即此處爲National)各級(州)。複雜的select語句應該只讀取較高的級別而忽略較低的級別

+------+--+--------+-----------+ 
| Name | | Level    | 
+------+--+--------+-----------+ 
| A | | state   | 
| B | | State   | 
| C | | state   | 
| A | | National   | 
+------+--+--------+-----------+ 

該查詢應該爲我的國家一級的記錄只取一次記錄,應該忽略州級別。 預先感謝您。

回答

0

您可以使用ROW_NUMBER給行列中來的最高水平,再挑取其最高..

模式:

CREATE TABLE #TAB(Name VARCHAR(50), LevelS VARCHAR(50)) 
INSERT INTO #TAB 
SELECT 'A','state' 
UNION ALL 
SELECT 'B','State' 
UNION ALL 
SELECT 'C','state' 
UNION ALL 
SELECT 'A','National' 

現在不要選擇像下面

SELECT * FROM (
SELECT ROW_NUMBER() OVER(PARTITION BY Name ORDER BY 
    CASE WHEN LevelS='state' THEN 2 
     WHEN LevelS='National' THEN 1 END) SNO 
,NAME 
,LevelS FROM #TAB 
)A 
WHERE SNO=1 

結果:

+-----+------+----------+ 
| SNO | NAME | LevelS | 
+-----+------+----------+ 
| 1 | A | National | 
| 1 | B | State | 
| 1 | C | state | 
+-----+------+----------+ 
相關問題