选择具有随机ID的不同两列

时间:2016-03-14 09:37:03

标签: sql random db2 distinct

我希望获得每个设计的明确记录,并输入每个记录的随机ID 无法使用

select distinct Design, Type, ID from table

它将返回所有值 这是我表的结构

Design | Type | ID
old chair 1
old table 2
old chair 3
new chair 4
new table 5
new table 6
newest chair 7

可能的结果

Design | Type | ID
old table 2
old chair 3
new chair 4
new table 6
newest chair 7

3 个答案:

答案 0 :(得分:4)

如果无关紧要,你可以随时取最大\最小值:

SELECT design,type,max(ID)
FROM YourTable
GROUP BY design,type

这不是随机的,它总是需要最大的\最小值,但似乎并不重要。

答案 1 :(得分:1)

试试这个:

select *
from (
select *, row_number() over (partition by Design,Type order by id desc) rowID
from @tab
) x
where rowID = 1

答案 2 :(得分:1)

希望这个能帮到你:

WITH CTE AS
(
    SELECT Design, Type, ID, ROW_NUMBER() OVER (PARTITION BY Design, 
                                                   Type ORDER BY id DESC) rid
    FROM table
)
SELECT Design, Type, ID FROM CTE WHERE rid = 1 ORDER BY ID