这3个月一直在做公司的报价系统的新功能开发和一些性能改版,经常性的遇见查询某个地区某个交易品下的最近一天的价格。在这里面用到一个表MD_HistoryPrices是保存历史报价记录。
第一种解决方式:用临时表:
临时表
1 WITH temp_2 AS(
2 SELECT AreaID ,GoodsId,MIN(PriceDate) as PriceDate FROM MD_HistoryPrices GROUP BY AreaID,GoodsId
3 )
4 SELECT pp.* FROM MD_HistoryPrices pp , temp_2 tt WHERE pp.AreaID = tt.AreaID AND pp.GoodsId = tt.GoodsID AND CONVERT(VARCHAR(10), pp.PriceDate,120)=CONVERT(VARCHAR(10),tt.PriceDate,120)
第二种解决方式:相互关联的子查询:
相互关联的子查询
1 SELECT * FROM MD_HistoryPrices pp WHERE pp.PriceDate = (SELECT MIN(ss.PriceDate) FROM MD_HistoryPrices ss WHERE ss.AreaID =pp.AreaID AND ss.GoodsId = pp.GoodsId)
如果从性能上面考虑,第二种解决方式性能高
项目中生成原始报价有个需求,用最近一天的报价来生成今天(某个用户、地区和交易品下)的报价,如果最近一天不存在,那么今天这个用户交易品和地区的价格就是0;
sql_1
1 with temp_1 AS(
2 SELECT ID AS GoodsID FROM MD_Goods WHERE TypeId = 1
3 ),
4 temp_2 AS(
5 SELECT rr.AdminUserId,rr.GoodsId,rr.AreaId,rr.Percentage FROM MD_PriceRule rr LEFT JOIN temp_1 tt ON 1=1 WHERE rr.Percentage>0 AND rr.GoodsId = tt.GoodsID
6 )
7 SELECT tt.AdminUserId,tt.AreaId,tt.GoodsId,ISNULL(pp.GuidePrice,0),GETDATE() AS GuidePrice FROM temp_2 tt LEFT JOIN MD_HistoryPrices pp ON tt.AreaId= pp.AreaID AND tt.GoodsId = pp.GoodsId AND CONVERT(VARCHAR(10),pp.PriceDate,120)=(
8 SELECT CONVERT(VARCHAR(10),MAX(PriceDate),120) FROM MD_HistoryPrices p1
9 WHERE p1.AreaID=pp.AreaID AND p1.GoodsId = pp.GoodsId AND CONVERT(VARCHAR(10),p1.PriceDate,120)< CONVERT(VARCHAR(10),GETDATE(),120)
10 )
查询每个地区的最早一天的报价信息:
View Code
1 SELECT aa.CnName , ISNULL((select MIN(pp.PriceDate) from MD_HistoryPrices pp WHERE pp.AreaID = aa.ID),GETDATE()) FROM MD_AreaInfo aa