我有一张名为Orders
的表格。它有id
,orderid
,qty
,cost
,location
,currency
......等列。
我必须将此订单表中的值插入到给定order id
的另一个表中,但问题出在currency
。
对于每个orderid
,order
表格中会有多行,每行可能有差异currency
。
因此,当从此表中为orderid
插入新行时,我需要计算不同的货币并插入具有最高计数的货币。
如何比较列中不同值的计数?这是在SQL Server中。
答案 0 :(得分:2)
with cte as
(
select orderid,currency, row_number() over
(partition by orderid,currency order by orderid,currency) rownumber
from orders
)
select cte.orderid,cte.currency
from cte
join
(select orderid,max(rownumber) rownumber2
from cte group by orderid) A
on cte.orderid=a.orderid and cte.rownumber=a.rownumber2
演示SQLFIDDLE:http://sqlfiddle.com/#!3/1c046/25
感谢bluefeet提供样本数据
答案 1 :(得分:1)
您的要求并不十分清楚,但您似乎可以使用以下内容:
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
这将返回包含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 |
答案 2 :(得分:0)
如果我正确理解了您的问题,那么您正在尝试在Orders
表中找到具有最多记录的货币,并给出具体的OrderId
?
这样的事情 - 如果多个货币用相同的计数表示,它可以返回多个记录吗?
SELECT MAX(c.CurrencyCount), c.currency
FROM
(
SELECT currency, Count(currency) as CurrencyCount
FROM Orders
WHERE OrderId = 12345
GROUP BY currency
) c
GROUP BY c.currency
答案 3 :(得分:0)
据我所知,您是否希望将行从Orders迁移到otherTable,包括另外两列:maxCurrency和totalDistinctCurrency。
如果我的理解是正确的,那么你可以这样做:
INSERT INTO otherTable(
maxCurrency,
totalDistinctCurrency,
otherColsFromOrders)
SELECT
MAX(currency),
COUNT(DISTINCT currency),
*
FROM Orders
WHERE orderid = SOME_ORDER_ID_YOU_WANT;
注意两点:
希望它有所帮助!
答案 4 :(得分:0)
还有一个选项
SELECT *
FROM Orders t
WHERE EXISTS(
SELECT CASE WHEN MAX(COUNT(t2.currency)) OVER() = COUNT(t2.currency) THEN t2.currency END
FROM Orders t2
WHERE t2.orderid = t.orderid
GROUP BY t2.currency
INTERSECT
SELECT t.currency
)
SQLFiddle上的演示