2017-06-13 42 views
0

我有一個select語句。爲唯一鍵選擇最大日期行

  SELECT x.ndc_id 
     ,z.attr_val AS trade_name 
     ,x.quote_price 
     ,x.eff_dt FROM contract_ndc_brg x 
     LEFT JOIN ndc_attr AS z ON z.field_id = 150 
     where contract_num_val = (
      SELECT item_name 
      FROM [contract] 
      WHERE item_id = 184 
      ) 

enter image description here

公告有兩行具有相同ndc_id。我想要這些結果,但每個ndc_id只有一個結果,其中最高的爲eff_dt

我嘗試添加where子句:

  SELECT x.ndc_id 
     ,z.attr_val AS trade_name 
     ,x.quote_price 
     ,x.eff_dt FROM contract_ndc_brg x 
     LEFT JOIN ndc_attr AS z ON z.field_id = 150 
     where contract_num_val = (
      SELECT item_name 
      FROM [contract] 
      WHERE item_id = 184 
      ) and x.eff_dt = (select max(eff_dt) from contract_ndc_brg where contract_num_val = (
      SELECT item_name 
      FROM [contract] 
      WHERE item_id = 184 
      )) 

我這個想通了,問題是,它返回的任何行的最大日期。

我該如何解決我在做什麼錯?

+1

你嘗試用'GROUP BY'? – Sami

+0

@Sami你能否詳細說明一下? –

回答

1

ROW_NUMBER()是你的朋友:

with q as 
(
     SELECT x.ndc_id 
     ,z.attr_val AS trade_name 
     ,x.quote_price 
     ,x.eff_dt 
     ,row_number() over (partition by nc_id order by eff_dt desc) rn 
     FROM contract_ndc_brg x 
     LEFT JOIN ndc_attr AS z ON z.field_id = 150 
     where contract_num_val = (
      SELECT item_name 
      FROM [contract] 
      WHERE item_id = 184 
      ) 
) 
select nc_id, trade_name, quote_price, eff_dt 
from q 
where rn = 1 
+0

我得到:Msg 156,Level 15,State 1,Line 7 關鍵字'over'附近的語法錯誤。 Msg 102,Level 15,State 1,Line 14 ')'附近語法不正確。 –

+0

固定錯字。從與eff_dt開始相同的行 –

+0

非常感謝! –

相關問題