我有一个名为Orders
的表。它有列id
、orderid
、qty
、cost
、location
、货币
...等。
我必须将此订单表中的值插入到给定订单 ID
的另一个表中,但问题出在货币
上。
对于每个 orderid
,order
表中都会有多行,并且每行可以有不同的currency
。
因此,在从此表中为 orderid
插入新行时,我需要获取不同货币的计数并插入计数最高的货币。
如何比较列中不同值的计数?这是在 SQL Server 中。
最佳答案
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 提供示例数据
关于sql - 比较表中的列值计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14348625/