您的要求并不完全清楚,但似乎您可以使用这样的东西:
select o.id,
o.orderid,
o.currency,
o.cost
from orders o
inner join
(
select orderid, currency,
CountCurrency,
max(CountCurrency) over(partition by orderid) mx
from
(
select orderid, currency, count(currency) CountCurrency
from orders
group by orderid, currency
) o
) m
on o.orderid = m.orderid
and o.currency = m.currency
where m.CountCurrency = m.mx
order by o.orderid, o.id
请参阅带有演示的 SQL Fiddle
这将返回包含出现最多的货币的所有行orderid
。使用样本数据:
CREATE TABLE orders
([id] int, [orderid] int, [currency] varchar(3), [cost] int)
;
INSERT INTO orders
([id], [orderid], [currency], [cost])
VALUES
(1, 10, 'USD', 1000),
(2, 10, 'EUR', 522),
(3, 10, 'USD', 999),
(4, 10, 'INR', 999),
(5, 20, 'TST', 557),
(6, 25, 'GRB', 24),
(7, 20, 'TST', 78),
(8, 30, 'HYT', 3)
;
结果是:
| ID | ORDERID | CURRENCY | COST |
----------------------------------
| 1 | 10 | USD | 1000 |
| 3 | 10 | USD | 999 |
| 5 | 20 | TST | 557 |
| 7 | 20 | TST | 78 |
| 6 | 25 | GRB | 24 |
| 8 | 30 | HYT | 3 |