zoukankan      html  css  js  c++  java
  • 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)
    效果图:

     

  • 相关阅读:
    NFS 服务器实验
    ssh服务实验
    dhcp服务实验
    邮件服务器
    搭建 DNS 服务器
    搭建 web 服务器
    Feign下的数据传递
    基于Spring Cloud Feign的Mock工具
    Git 使用注意事项
    基于redisson的延迟队列
  • 原文地址:https://www.cnblogs.com/cici_liang/p/2201801.html
Copyright © 2011-2022 走看看