现有数据库为每个煤矿企业的应淘汰和已淘汰设备数目,并且每个煤矿的属性(国有重点、地方、乡镇)也有相应字段,现在想通过一条语句查询到下面这种格式的数据(因为涉及到.net中的表格控件,所以尽量就用一条语句啦),求问该怎么写SQL语句呢??谢谢谢谢~~~

解决方案 »

  1.   

    用case语句
    with t as 
    (select sum(case when sx1='应淘汰' and sx2='国有重点' then sl else 0 end) GYZD1,
                sum(case when sx1='应淘汰' and sx2='国有地方' then sl else 0 end) GYDF1,
                sum(case when sx1='应淘汰' and sx2='乡镇煤矿' then sl else 0 end) XZMK1,
                sum(case when sx1='已淘汰' and sx2='国有重点' then sl else 0 end) GYZD2,
                sum(case when sx1='已淘汰' and sx2='国有地方' then sl else 0 end) GYDF2,
                sum(case when sx1='已淘汰' and sx2='乡镇煤矿' then sl else 0 end) XZMK2
      yourTable)
    select GYZD1+GYDF1+XZMK1 as HJ1,GYZD1,GYDF1,XZMK1,GYZD2+GYDF2+XZMK2 as HJ2,GYZD2,GYDF2,XZMK2
      from t;
      

  2.   

    在存储过程中,先建一个临时表,再把每一项更新到临时表中,再select * 这个临时表。一般做统计报表都是这么干,查询速度快。
      

  3.   


    select
    case when 设备类型  = 淘汰设备 and 企业类型 = 国有重点 then 
         xxxxxx
    end,
    case when 设备类型  = 淘汰设备 and 企业类型 = 国有地方 then 
         xxxxxx
    end,
    ...以此类推
    from table group by 设备类型,企业类型