關於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
--------------------------------------