• SQL语句—数据分组


    ---创建SQL语句

    create table #DepartCost
    (
    id
    int,
    Department
    varchar(20),
    Material
    varchar(20),
    Number int
    )
    insert into #DepartCost values
    (
    1,'厂房1','材料1',1),
    (
    1,'厂房2','材料2',2),
    (
    1,'厂房1','材料3',1),
    (
    1,'厂房3','材料3',1),
    (
    1,'厂房2','材料3',1),
    (
    1,'厂房3','材料1',1),
    (
    1,'厂房1','材料1',2),
    (
    1,'厂房1','材料2',1),
    (
    1,'厂房1','材料3',1)
    方法一:

    select Department,
    sum(case Material when '材料1' then Number else 0 end) as [材料1],
    sum(case Material when '材料2' then Number else 0 end) as [材料2],
    sum(case Material when '材料3' then Number else 0 end) as [材料3]
    from #DepartCost
    group by Department
    方法二:

    declare @sql varchar(1000)
    set @sql = 'select Department '
    select @sql = @sql+', sum(case Material when '''+Material+''' then Number else 0 end) as ['+Material+']' from
    (
    select distinct Material from #DepartCost) as a
    select @sql = @sql + ' from #DepartCost group by Department '
    exec(@sql)
    效果图:

     

  • 相关阅读:
    POJ_1485_dp
    POJ_1376_bfs
    [noi1994]海盗
    [noi1755]Trie
    [luogu3733]八纵八横
    [noi1774]array
    [noi1773]function
    [noi1754]SA
    [noi1779]D
    [bzoj4873]寿司餐厅
  • 原文地址:https://www.cnblogs.com/cici_liang/p/2201801.html
Copyright © 2020-2023  润新知