问题
Possible Duplicate:
Delete duplicate records from a SQL table without a primary key
I have data:
SELECT
a
, b
FROM
(
select a = 1, b = 30
union all
select a = 2, b = 50
union all
select a = 3, b = 50
union all
select a = 4, b = 50
union all
select a = 5, b = 60
) t
I have to get output (next (order by a) dublicate records should be excluded from result set):
a b
----------- -----------
1 30
2 50
3 50 -- should be excluded
4 50 -- should be excluded
5 60
回答1:
SELECT
min(a) as a
, b
FROM
(
select a = 1, b = 30
union all
select a = 2, b = 50
union all
select a = 3, b = 50
union all
select a = 4, b = 50
union all
select a = 5, b = 60
) t
GROUP BY b
ORDER BY a
回答2:
In oracle I was able to do this using a group by clause, you should be able to do similar.
select min(a), b
from (select 1 a, 30 b
from dual
union all
select 2 a, 50 b
from dual
union all
select 3 a, 50 b
from dual
union all
select 4 a, 50 b
from dual
union all
select 5 a, 60 b from dual)
group by b;
edit: looks like someone else came up with a MS sql solution, I'll leave this here for posterity though.
回答3:
The easiest way to do this is with a simple GROUP BY
:
SELECT
a
, b
INTO #tmp
FROM
(
select a = 1, b = 30
union all
select a = 2, b = 50
union all
select a = 3, b = 50
union all
select a = 4, b = 50
union all
select a = 5, b = 60
) t
SELECT DISTINCT MIN(a) AS a,b
FROM #tmp
GROUP BY b
ORDER BY a
来源:https://stackoverflow.com/questions/7447675/duplicates-removing