为相同字段的许多不同结果汇总数据

时间:2014-08-27 17:55:33

标签: sql sql-server-2008

我正在努力寻找一种更好的方法来编写这个sql server代码2008.它工作正常,数据准确。我问的原因是,我将被要求为其他几个报告执行此操作,并希望减少维护的代码量。 我怎样才能得到一个字段,其中我在每个字段中总结是/否/ - (短划线)而不像我在代码中那样进行单独的求和。每个表都是一个月的详细数据,我总结在CTE中使用。我更改了每个月的表名和Union All将数据放在一起。有一个更好的方法吗。这是一小段代码。谢谢你的帮助。

WITH H AS (
SELECT 'August' AS Month_Name
    , SUM(CASE WHEN G.FFS = '-'     THEN 1 ELSE 0 END) AS FFS_Dash
    , SUM(CASE WHEN G.FFS = 'Yes'   THEN 1 ELSE 0 END) AS FFS_Yes
    , SUM(CASE WHEN G.FFS = 'No'    THEN 1 ELSE 0 END) AS FFS_No
    , SUM(CASE WHEN G.DNA = '-'     THEN 1 ELSE 0 END) AS DNA_Dash
    , SUM(CASE WHEN G.DNA = 'Yes'   THEN 1 ELSE 0 END) AS DNA_Yes
    , SUM(CASE WHEN G.DNA = 'No'    THEN 1 ELSE 0 END) AS DNA_No
FROM table08 G )
, G AS (
SELECT 'July' AS Month_Name
    , SUM(CASE WHEN G.FFS = '-'     THEN 1 ELSE 0 END) AS FFS_Dash
    , SUM(CASE WHEN G.FFS = 'Yes'   THEN 1 ELSE 0 END) AS FFS_Yes
    , SUM(CASE WHEN G.FFS = 'No'    THEN 1 ELSE 0 END) AS FFS_No
    , SUM(CASE WHEN G.DNA = '-'     THEN 1 ELSE 0 END) AS DNA_Dash
    , SUM(CASE WHEN G.DNA = 'Yes'   THEN 1 ELSE 0 END) AS DNA_Yes
    , SUM(CASE WHEN G.DNA = 'No'    THEN 1 ELSE 0 END) AS DNA_No
FROM table07 G )
select * from H 
UNION ALL
select * from G 

1 个答案:

答案 0 :(得分:2)

怎么样:

SELECT Month_Name,
       SUM(CASE WHEN G.FFS = '-'     THEN 1 ELSE 0 END) AS FFS_Dash,
       SUM(CASE WHEN G.FFS = 'Yes'   THEN 1 ELSE 0 END) AS FFS_Yes,
       SUM(CASE WHEN G.FFS = 'No'    THEN 1 ELSE 0 END) AS FFS_No,
       SUM(CASE WHEN G.DNA = '-'     THEN 1 ELSE 0 END) AS DNA_Dash,
       SUM(CASE WHEN G.DNA = 'Yes'   THEN 1 ELSE 0 END) AS DNA_Yes,
       SUM(CASE WHEN G.DNA = 'No'    THEN 1 ELSE 0 END) AS DNA_No
FROM ((select 'July' as Month_Name, G.*
       from table07 G
      ) union all
      (select 'August', H.*
       from table08 H
      )
     ) gh
GROUP BY Month_Name;

但是,具有相同结构的表通常是数据库设计不佳的标志。您应该有一个表格,该列表示月份。