当前位置: 代码迷 >> Sql Server >> 求一条sql查询语句解决思路
  详细解决方案

求一条sql查询语句解决思路

热度:21   发布时间:2016-04-27 15:30:14.0
求一条sql查询语句
数据库是sql server express 2005的;

表名是table1;
表的结构:productid(产品代码)、price(价格)、discount(折扣)、supplyid(供应商代码)
主键是productid+supplyid

表的内容:
productid price discount supplyid
0001 0.5 0.02 1
0001 0.4 0.03 2
0001 0.4 0.01 3
0002 1 0 1
0002 0.8 0 2
0002 0.9 0 3
0003 0.8 0.02 1
0003 0.7 0.01 2
0003 0.8 0.03 3


无论纪录有多少条,supplyid只有3个,即为1,2,3
productid可能有很多,上面的只是例子
寻找一条sql查询语句,要求:
查出每一个productid,discount最小的那一行,对于每个productid,只给出合适的一条纪录
上面那表查询的结果应该为(对于discount一样的,给出任一行就行了)
0001 0.4 0.01 3
0002 1 0 1
0003 0.4 0.01 3

谢谢啦


------解决方案--------------------
use CTE (common table expression, only available in SQL Server 2005)


SQL code
create table table1(productid varchar(10), price float, discount float, supplyid int)insert table1select '0001', 0.5, 0.02, 1union all select '0001', 0.4, 0.03, 2union all select '0001', 0.4, 0.01, 3union all select '0002', 1, 0, 1union all select '0002', 0.8, 0, 2union all select '0002', 0.9, 0, 3union all select '0003', 0.8, 0.02, 1union all select '0003', 0.7, 0.01, 2union all select '0003', 0.8, 0.03, 3With cte AS(select row_number() over (order by productid, discount) as rowid, productid, price, discount, supplyid  from table1)select c.productid, c.price, c.discount, c.supplyid from cte cJOIN (select productid, min(rowid) as rowid from ctegroup by productid)t ON c.productid = t.productid AND c.rowid = t.rowid
  相关解决方案