忽略GROUP BY的值的总和 - SQL SERVER 2008

时间:2016-09-28 08:29:22

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

编写了一个查询来提取数据和SUM区域值

SELECT
rtrim(fmb0.reg_code) as Region,
RTRIM(FMB0.COUNTRY) AS COUNTRY,
RTRIM(FMB0.BLDGCODE) AS BLDGCODE,
(CASE WHEN FMB0.BLDGSTATUS = '' THEN 'RECORD'
ELSE FMB0.BLDGSTATUS END) AS SOURCE,
(CASE
WHEN FMA0.SPACETYPE = 'U-TLS-AS' THEN round(SUM(fma0.AREA),3)
ELSE round(SUM(fma0.USABLE),3) END) as [CHARGEABLE AREA],
(CASE 
WHEN len(rtrim(fma0.group_))<1 THEN '**Unassigned**'  
ELSE RTRIM(FMA0.GROUP_) END) AS [COST CODE], 
(CASE 
WHEN len(rtrim(fma0.group_))<1 THEN '**Unassigned Space**' 
WHEN len(rtrim(fma0.group_))>1 AND rtrim(FMG0.GROUPDESC) IS NULL          THEN '**Inactive Cost Code**' 
ELSE RTRIM(FMG0.GROUPDESC) END) AS [COST CENTRE]

FROM FMA0 

LEFT JOIN FMB0 ON FMA0.BLDGCODE = FMB0.BLDGCODE
LEFT JOIN FMG0 ON FMA0.GROUP_ = FMG0.GROUP_

GROUP BY FMB0.BLDGCODE, FMA0.FLOORCODE,  FMA0.GROUP_, FMG0.GROUPDESC, FMG0.GROUPDESC3, FMB0.BLDGSTATUS, FMB0.COUNTRY, FMB0.REG_CODE,FMA0.SPACETYPE

因为我必须使用SPACETYPE来确定从AREA中取出哪个字段,我需要在GROUP BY子句中包含SPACETYPE。这意味着我看到SPACETYPE分割出的结果,即使我没有在SELECT语句中直接请求它。

Region  COUNTRY   BLDGCODE  SOURCE  FLOORCODE   CHARGEABLE AREA COST CODE       COST CENTRE
ASP     Hong Kong   BLDG01  CAD         28      39.016          **Unassigned**  **Unassigned Space**
ASP     Hong Kong   BLDG01  CAD         28      1217.146        **Unassigned**  **Unassigned Space**
ASP     Hong Kong   BLDG01  CAD         28      1506.181        **Unassigned**  **Unassigned Space**
ASP     Hong Kong   BLDG01  CAD         28      458.765         **Unassigned**  **Unassigned Space**
ASP     Hong Kong   BLDG01  CAD         28      1000.711        **Unassigned**  **Unassigned Space** 

如何按特定代码划分特定BLDGCODE中所有SPACETYPES的所有区域

1 个答案:

答案 0 :(得分:2)

尝试使用公用表表达式获取详细信息然后汇总:

WITH CTE
AS
(
   SELECT rtrim(fmb0.reg_code) as Region,
          RTRIM(FMB0.COUNTRY) AS COUNTRY,
          RTRIM(FMB0.BLDGCODE) AS BLDGCODE,
          (CASE WHEN FMB0.BLDGSTATUS = '' THEN 'RECORD'
                ELSE FMB0.BLDGSTATUS END) AS SOURCE,
          (CASE WHEN FMA0.SPACETYPE = 'U-TLS-AS' THEN round(fma0.AREA,3)
                ELSE round(fma0.USABLE,3) END) as [CHARGEABLE AREA],
          (CASE WHEN len(rtrim(fma0.group_))<1 THEN '**Unassigned**'  
                ELSE RTRIM(FMA0.GROUP_) END) AS [COST CODE], 
          (CASE WHEN len(rtrim(fma0.group_))<1 THEN '**Unassigned Space**' 
                WHEN len(rtrim(fma0.group_))>1 
                   AND rtrim(FMG0.GROUPDESC) IS NULL THEN '**Inactive Cost Code**' 
                ELSE RTRIM(FMG0.GROUPDESC) END) AS [COST CENTRE]
  FROM FMA0 
  LEFT JOIN FMB0 ON FMA0.BLDGCODE = FMB0.BLDGCODE
  LEFT JOIN FMG0 ON FMA0.GROUP_ = FMG0.GROUP_
)
SELECT Region, Country, BLDGCODE, Source, 
       (SUM([CHARGEABLE AREA]) AS [Chargeable Area], [COST CODE],[COST CENTRE]
FROM CTE
GROUP BY BLDGCODE, [Cost Code], [Cost Centre], Source, COUNTRY, Region