今天要寫一物料成本的報表。
背景:系統中乙個物料可能對應多個**商 itemvend(rank),乙個物料也可能對應多個**itemvendprice
很自然想到 :
根據生效日期按降序排列,取top 1
select top 1f.item,f.vend_num,f.effect_date ,f.brk_cost##1
from itemvendprice f,itemvend g where f.item=g.item and f.vend_num=g.vend_num and g.rank=1) b
order by f.effect_date desc
可是不能取得所有物料的**
想到用max函式
select b.item,b.vend_num,max(b.effect_date) as effect_date, b.brk_cost##1from
(select f.item,f.vend_num,f.effect_date
from itemvendprice f,itemvend g where f.item=g.item and f.vend_num=g.vend_num and g.rank=1) b
group by b.item,b.vend_num
語法錯誤--單價成本不同
故先不去單價成本,最後關聯之
select c.item,c.vend_num,c.effect_date,c.brk_cost##1 from itemvendprice c,
(select b.item,b.vend_num,max(b.effect_date) as effect_date from
(select f.item,f.vend_num,f.effect_date
from itemvendprice f,itemvend g where f.item=g.item and f.vend_num=g.vend_num and g.rank=1) b
group by b.item,b.vend_num) a
where c.item=a.item and c.vend_num=a.vend_num and c.effect_date=a.effect_date
測試結果ok -----
mysql查詢group by分組最新記錄資料
先group by得到分組每乙個的max id 即是最新記錄,之後通過inner join關聯得到最新記錄表。執行效率 0.031 sec select b.from table name b inner join select max id as id from table name group ...
SQL查詢最新的資料
在網上看了好多的查詢最大資料的 本人也提供了乙個解決思路 select from table where pro id 111 and create time in select max create time from table 查詢效率應該比下面的sql效率高一點 select from ta...
MYSQL 分組查詢最新的資料
第一種前提是資料表設計id自增select from t user where id in select max id from t user group by user id 第二種對子查詢進行limit限制,適用於明確資料量不會超過多少的場景,否則查不到全部資料select from selec...