汇总 SQL 数据 - MS SQL 服务器 2008

Aggregate SQL data - MS SQL server 2008

我在按订单号对数据进行分组并汇总 "support columns" 时遇到一些问题,同时总是选择 "highest" 值。

╔═════════════╦══════════════╦════════════════╗
║ OrderNumber ║ PhoneSupport ║ ServiceSupport ║
╠═════════════╬══════════════╬════════════════╣
║ 0000000001  ║ 0020         ║                ║
║ 0000000001  ║ 0010         ║ 0030           ║
║ 0000000001  ║ 0010         ║ 0020           ║
║ 0000000002  ║              ║ 0030           ║
║ 0000000002  ║ 0030         ║                ║
║ 0000000003  ║ 0020         ║                ║
║ 0000000003  ║ 0030         ║                ║
╚═════════════╩══════════════╩════════════════╝

在这个例子中,输出应该是这样的。

╔═════════════╦══════════════╦════════════════╗
║ OrderNumber ║ PhoneSupport ║ ServiceSupport ║
╠═════════════╬══════════════╬════════════════╣
║ 0000000001  ║ 0020         ║ 0030           ║
║ 0000000002  ║ 0030         ║ 0030           ║
║ 0000000003  ║ 0030         ║                ║
╚═════════════╩══════════════╩════════════════╝

到目前为止,我经常在各种论坛上阅读有关游标的内容,但我不喜欢使用它。

我的想法是使用 over 子句,但我不确定它是否适合这种情况。

使用 GROUP BY,在您想要 "highest" 值的列上执行 MAX

select OrderNumber, max(PhoneSupport), max(ServiceSupport)
from tablename
group by OrderNumber

您可以使用 Group ByMax,然后将查询包装在父级中以对聚合列执行 Order By。示例如下。

select * 
from (
    select OrderNumber, max(PhoneSupport) as PhoneSupport, max(ServiceSupport)  as ServiceSupport
    from tablename
    group by OrderNumber) aa
Order By aa.PhoneSupport