在sql中汇总组中的数据?

时间:2014-08-19 11:14:28

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我不确定在下面的SQL查询中应该写什么来显示以下结果:

数据: enter image description here

颜色是独特的栏目......

结果:

enter image description here

1 个答案:

答案 0 :(得分:6)

select color as [name/color], value
from your_table
union all
select name, sum(value)
from your_table
group by name

如果您需要特定订单,那么您可以

select [name/color], value 
from 
(
    select color as [name/color], value, name as order_column
    from your_table
    union all
    select name, sum(value), name
    from your_table
    group by name
) x 
order by order_column