多个结果 - 仅需最新价格

时间:2018-04-13 23:50:07

标签: sql sql-server

我需要找到一些物品的最新价格

这是我的疑问:

 SELECT 
 MAX("POPORH1"."DATE") as "PO DATE",
 "ICSHEH"."DOCNUM", 
 "ICSHEH"."TRANSDATE", 
 "ICSHEH"."FISCYEAR", 
 "ICSHEH"."FISCPERIOD", 
 "ICSHEH"."REFERENCE", 
 "ICSHED"."ITEMNO", 
 "ICSHED"."ITEMDESC", 
 "ICSHED"."LOCATION", 
 "ICSHED"."QUANTITY", 
 "ICSHED"."UNIT", 
 "POPORL"."UNITCOST"

 FROM   (("CABDAT"."dbo"."ICSHEH" "ICSHEH" 
 INNER JOIN 
 "CABDAT"."dbo"."ICSHED" "ICSHED" ON "ICSHEH"."SEQUENCENO"="ICSHED"."SEQUENCENO") 
 INNER JOIN "CABDAT"."dbo"."POPORL" "POPORL" ON "ICSHED"."ITEMNO"="POPORL"."ITEMNO") 
 INNER JOIN "CABDAT"."dbo"."POPORH1" "POPORH1" ON "POPORL"."PORHSEQ"="POPORH1"."PORHSEQ"
 WHERE  "ICSHED"."SEQUENCENO"=55873
 group by
 "ICSHEH"."DOCNUM", 
 "ICSHEH"."TRANSDATE", 
 "ICSHEH"."FISCYEAR", 
 "ICSHEH"."FISCPERIOD", 
 "ICSHEH"."REFERENCE", 
 "ICSHED"."ITEMNO", 
 "ICSHED"."ITEMDESC", 
 "ICSHED"."LOCATION", 
 "ICSHED"."QUANTITY", 
 "ICSHED"."UNIT", 
 "POPORL"."UNITCOST"

此查询返回多个结果

结果如下:

"PODATE"='20180405' "ITEMNO"='2944'  "UNITCOST"='0.266750'
"PODATE"='20180405' "ITEMNO"='2946'  "UNITCOST"='0.266750'
"PODATE"='20170208' "ITEMNO"='2944'  "UNITCOST"='0.250780'
"PODATE"='20170208' "ITEMNO"='2944'  "UNITCOST"='0.250780'
"PODATE"='20170208' "ITEMNO"='2946'  "UNITCOST"='0.250780'
"PODATE"='20170208' "ITEMNO"='2946'  "UNITCOST"='0.250780'

我只需要 " PODATE" =' 20180405' " ITEMNO" =' 2944' " UNITCOST" =' 0.266750' " PODATE" =' 20180405' " ITEMNO" =' 2946' " UNITCOST" =' 0.266750'

我正在学习SQL,所以请耐心等待我的无知......

非常感谢!

2 个答案:

答案 0 :(得分:1)

您只需要row_number()

 WITH cte as (
     SELECT *,  ROW_NUMBER() OVER (PARTITION BY "ITEMNO" ORDER BY  "PODATE" DESC) as rn
     FROM "ICSHED"  -- or join tables
     WHERE "ICSHED"."SEQUENCENO"=55873
 )
 SELECT *
 FROM cte where rn = 1

或者,如果您只需要最高值而不进行任何分组,则可以使用TOP 1

 SELECT TOP 1 *
 FROM "ICSHED"  -- or join tables
 WHERE "ICSHED"."SEQUENCENO"=55873
 ORDER  "PODATE" DESC

答案 1 :(得分:0)

根据我的理解,您希望前2行包含最近的日期。所以我试试这个,

  select top 2 * from yourtable order by dateCol desc