首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

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

2012-02-23 
求一条sql查询语句数据库是sql server express 2005的;表名是table1;表的结构:productid(产品代码)、price(

求一条sql查询语句
数据库是sql server express 2005的;

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

表的内容:
productidpricediscountsupplyid
00010.50.021
00010.40.032
00010.40.013
0002101
00020.802
00020.903
00030.80.021
00030.70.012
00030.80.033


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

谢谢啦


[解决办法]
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 

热点排行