SQL查找不同的多个值

时间:2017-02-13 18:03:52

标签: sql sql-server-2008

我有一个包含房间信息的表格,其中包含BLDGCODE的列和COSTCODE的另一列。建筑物中的每个房间(BLDGCODE)只能分配一个成本代码,这些代码可以是相同的值或不同的值。

我试图编写一个脚本,只显示分配给多个房间的多个不同成本代码的建筑物,例如,几个房间可能有成本代码ABC,其他999就是我想要识别和报告的内容。我尝试过以下思考CTE会得到结果,但是我仍然看到建筑物中只有一个成本代码,这些代码在建筑物中的多个房间重复出现。

with CTE
as (
    select rtrim(fmb0.reg_code) as Region,
        rtrim(Country) as Country,
        rtrim(fmb0.BLDGCODE) as BLDGCODE,
        (
            case 
                when FMB0.BLDGSTATUS = 'CAD'
                    then 'Yes'
                else 'No'
                end
            ) as CAD,
        group_ as GROUP_,
        fma0.usable,
        fmb0.nia,
        fmb0.niahprev
    from fmb0
    left join fma0 on fmb0.bldgcode = fma0.bldgcode
    left join fmey on fmb0.propsubtyp = fmey.ey_key
    left join fme2 on fmb0.country = fme2.descrip
    where fme2.is_live = 1
        and fmey.bau = 1
        and fmb0.bldgcode not like 'xx%'
        and fma0.bldgcode like 'cn%'
    )
select CTE.Region,
    CTE.Country,
    CTE.BLDGCODE,
    CTE.GROUP_,
    sum(cte.usable) as AREA,
    cte.nia,
    cte.niahprev,
    CTE.CAD
from CTE
where CTE.CAD = 'No'
group by CTE.BLDGCODE,
    cte.group_,
    cte.country,
    cte.region,
    cte.nia,
    cte.cad,
    cte.niahprev
having count(CTE.GROUP_) > 1
order by 1, 2, 3

如何删除那些尽管有多次出现且成本代码相同的建筑物,并且只显示那些有多个成本代码的建筑物不同的建筑物?

所以这是引用单个表的代码:

with CTE as (
select 
rtrim(fma0.BLDGCODE) as BLDGCODE, 
group_ as GROUP_,
fma0.usable
from fma0
where 
fma0.bldgcode like 'cn%'
)
select 
CTE.BLDGCODE,
CTE.GROUP_ AS COSTCODE,
sum(cte.usable) as AREA
from CTE
group by CTE.BLDGCODE, cte.group_
having count(CTE.GROUP_) > 1
order by 1

示例数据集将是:

RMID      BLDGCODE    COSTCODE    AREA
01.01     01          AA-01       10
01.02     01          AS-05       20
01.03     01          XY-99       30
01.04     01          XY-99       70
02.01     02          AA-01       10
02.02     02          AA-01       20
02.03     02          AA-01       20

预期结果将是:

BLDGCODE     COSTCODE     AREA
01           AA-01        10
01           AS-05        20
01           XY-99        100

BLDGCODE 02不会显示,因为它只有一个成本代码

由于

1 个答案:

答案 0 :(得分:1)

您希望所有这些行都包含多个代码,因此简单的聚合不起作用。您可以使用另一个带有窗口聚合的cte来执行相同的逻辑:

with CTE as (
select 
   rtrim(fma0.BLDGCODE) as BLDGCODE, 
   group_ as GROUP_,
   fma0.usable
from fma0
where fma0.bldgcode like 'cn%'
)
,counts as
 (
   select 
      CTE.BLDGCODE,
      CTE.GROUP_ AS COSTCODE,
      sum(cte.usable) as AREA,
      case when min(CTE.GROUP_) over (partition by CTE.BLDGCODE) 
             <> max(CTE.GROUP_) over (partition by CTE.BLDGCODE)
           then 1
           else 0
      end as flag
   from CTE
   group by CTE.BLDGCODE, cte.group_
 ) 
select *
from counts
where flag = 1