Select 没有排序依据的组最高记录
Select top record by group without order by
我的来源 table 看起来像这样
cust_id cust_name
1 John Smith
1 John K Smith
2 Mary B Snow
2 Mary Snow
我想return
cust_id cust_name
1 John Smith
2 Mary B Snow
其中一个 cust_name 值并不优于另一个值;我只想要每个 cust_id 一行,并附有任意 cust_name。
我正在使用
select cust_id, cust_name from customers
qualify 1 = row_number() over (partition by cust_id order by cust_name desc)
但是由于 order by
子句,我不能在子查询中使用它。
有没有一种方法可以在没有(概念上不必要的)排序的情况下做到这一点?
select cust_id, min(cust_name)
from customers
group by cust_id
您必须在 ORDER BY
子句中使用 SELECT NULL
。这样它就不会更改顺序并且 Row_Number 将按预期工作
试试这个
SELECT cust_id, cust_name FROM
(
SELECT cust_id, cust_name ,ROW_NUMBER() OVER (PARTITION BY cust_id ORDER BY (SELECT NULL)) RN
FROM customers
)Tmp WHERE RN = 1
如果不需要订购,只需运行这个:
SELECT cust_id, MAX(cust_name)
FROM customers
GROUP BY cust_id
这应该有效
select cust_id,
min(cust_name) as cust_name
from customers
group by cust_id
我的来源 table 看起来像这样
cust_id cust_name
1 John Smith
1 John K Smith
2 Mary B Snow
2 Mary Snow
我想return
cust_id cust_name
1 John Smith
2 Mary B Snow
其中一个 cust_name 值并不优于另一个值;我只想要每个 cust_id 一行,并附有任意 cust_name。
我正在使用
select cust_id, cust_name from customers
qualify 1 = row_number() over (partition by cust_id order by cust_name desc)
但是由于 order by
子句,我不能在子查询中使用它。
有没有一种方法可以在没有(概念上不必要的)排序的情况下做到这一点?
select cust_id, min(cust_name)
from customers
group by cust_id
您必须在 ORDER BY
子句中使用 SELECT NULL
。这样它就不会更改顺序并且 Row_Number 将按预期工作
试试这个
SELECT cust_id, cust_name FROM
(
SELECT cust_id, cust_name ,ROW_NUMBER() OVER (PARTITION BY cust_id ORDER BY (SELECT NULL)) RN
FROM customers
)Tmp WHERE RN = 1
如果不需要订购,只需运行这个:
SELECT cust_id, MAX(cust_name)
FROM customers
GROUP BY cust_id
这应该有效
select cust_id,
min(cust_name) as cust_name
from customers
group by cust_id