如何检索char列的最大出现值

时间:2012-09-24 12:57:38

标签: sql-server-2008

我在获取列的最大出现时遇到问题

 matnum   uom  amount
-------------------------------------
1234    EA   10
1234    CS   10
1234    EA    20
1235    CS   10
1235    CS    20

我的输出选择应该是

 matnum   uom  SUM(amount)
-------------------------------------
1234   EA (because EA occured Twice)    40
1235   CS                               30

请提供选择查询以获得所需结果

3 个答案:

答案 0 :(得分:1)

我在这里假设你想要的东西,但是:

SELECT A.matnum, B.uom, C.s AS [SUM(amount)]
FROM yourtable A
INNER JOIN (
    SELECT matnum, uom, 
        ROW_NUMBER() OVER (PARTITION BY matnum ORDER BY COUNT(*) DESC) AS rnm
    FROM yourtable
    GROUP BY matnum, uom
) B ON A.matnum = B.matnum AND B.rnm = 1
INNER JOIN (
    SELECT matnum, SUM(amount) AS s 
    FROM yourtable 
    GROUP BY matnum
) C ON A.matnum = C.matnum
GROUP BY A.matnum, B.uom, C.s

SQL Fiddle

答案 1 :(得分:0)

select matnum, 
       uom, 
       SUM(amount) as sum_amount
from your_table
group by matnum, uom

答案 2 :(得分:0)

select max(matnum) as matnum,max(uom) as uom,SUM(amount)
from yourtable
group by matnum,uom