|
|
|
|
你现在的位置:您现在的位置是: 中国ASP>>数据库>>sql server |
|
| distinct id的取法 |
|
关于distinct id的取法 型如表:t_test -------------------------------------- id(int) cost(int) des Autoid(id) -------------------------------------- 1 10 aaaa 1 1 15 bbbb 2 1 20 cccc 3 2 80 aaaa 4 2 100 bbbb 5 2 60 dddd 6 3 500 dddd 7 -------------------------------------- 要在其中取每一类id中间cost最大的所有纪录,很多网友都对此进行了讨论,对此,我提出一点自己的看法, 我认为用一条很难(对我而言)达到要求,同时也引出了一个问题,即:在SQL中定义自己的函数(/存储过程),达到特定的目的。具体对这个例子而言,可以这么写:
CREATE PROCEDURE sp_test AS begin SELECT * INTO #mytbl FROM t_test
SELECT id, MAX(cost) AS max_cost INTO #mytemp FROM t_test GROUP BY id HAVING (COUNT(*) > 1) DELETE #mytbl FROM #mytemp, #mytbl WHERE #mytbl.id = #mytemp.id AND #mytbl.cost <> #mytemp.max_cost
select * from #mytbl end
execute sp_test 返回: id(int) cost(int) des Autoid(id) -------------------------------------- 1 20 cccc 3 2 100 bbbb 5 3 500 dddd 7 --------------------------------------
以上是我在SQL 2000下调是通过的
|
|
|