2017-04-25 83 views
1

我使用Aginity WorkbenchNetezza數據庫,我試圖與特色三(可維護性)列中的任何一個的IS代碼基於它的最早日期返回的記錄。一個ICS_UID有多個記錄,但我只想返回記錄,其中最早出現的記錄是IS代碼。返回錄製最早日期

下面是我一直在嘗試使用的代碼,但它似乎是返回所有記錄的IS代碼的實例,而不是在where子句中選擇ICS_UID的所有實例。感謝任何幫助或建議。

SELECT 
ICS _UID, min(MOVEMENT_DATE) as MOVEMENT_DATE, CURRENT_A_SERVICABILITY_CODE, CURRENT_B_SERVICABILITY_CODE, 
CURRENT_C_SERVICABILITY_CODE 
FROM 
HUB_MOVEMENT 
WHERE 
ICS_UID IN (317517607,317962513,etc,etc…) 
AND CURRENT_A_SERVICABILITY_CODE = 'IS' OR CURRENT_B_SERVICABILITY_CODE = 'IS' OR CURRENT_C_SERVICABILITY_CODE = 'IS' 
GROUP BY 
ICS_UID, CURRENT_A_SERVICABILITY_CODE, 
CURRENT_B_SERVICABILITY_CODE, 
CURRENT_C_SERVICABILITY_CODE; 

回答

1

請勿使用GROUP BY。如果你想要一個記錄,則:

SELECT m.* 
FROM HUB_MOVEMENT m 
WHERE ICS_UID IN (317517607,317962513,etc,etc…) AND 
     'IS' IN (CURRENT_A_SERVICABILITY_CODE, CURRENT_B_SERVICABILITY_CODE , CURRENT_C_SERVICABILITY_CODE) 
ORDER BY MOVEMENT_DATE 
LIMIT 1; 

如果你想每ICS_UID一行,那麼你可以使用ROW_NUMBER()

SELECT m.* 
FROM (SELECT m.*, 
      ROW_NUMBER() OVER (PARTITION BY ICS_UID ORDER BY MOVEMENT_DATE) as seqnum 
     FROM HUB_MOVEMENT m 
     WHERE ICS_UID IN (317517607,317962513,etc,etc…) AND 
      'IS' IN (CURRENT_A_SERVICABILITY_CODE, CURRENT_B_SERVICABILITY_CODE , CURRENT_C_SERVICABILITY_CODE) 
    ) m 
WHERE seqnum = 1; 
+0

尼斯使用的 '是' IN(.....)正想着同樣的事縮短重複或陳述 – DKSan

+0

謝謝!我用你的第二個例子,它完美的作品!我是一個sql noob,但是以爲我和團隊一起走錯了路。 – gstatus