我设法编写了以下查询,该查询返回了我需要查看建筑物中楼层占用率和容量的结果。
select
fma0.bldgcode,
fma0.floorcode,
sum(fma0.occ) as Occupancy,
sum(CASE WHEN FMA0.SPACETYPE like 'A-OFF-%' OR
FMA0.SPACETYPE like 'A-WKS-%' THEN FMA0.CAPACITY
ELSE 0 END) as Capacity
from fma0
where fma0.bldgcode = 'tst01'
group by fma0.bldgcode, fma0.floorcode
order by fma0.bldgcode, fma0.floorcode
但是我需要添加什么才能获得另一列"占用/容量"的总和。
THKS
FTD
答案 0 :(得分:0)
SELECT
bldgcode,
floorcode,
Occupancy,
Capacity ,
Occupancy+Capacity AS allsum
FROM(
select
fma0.bldgcode,
fma0.floorcode,
sum(fma0.occ) as Occupancy,
sum(CASE WHEN FMA0.SPACETYPE like 'A-OFF-%' OR
FMA0.SPACETYPE like 'A-WKS-%' THEN FMA0.CAPACITY
ELSE 0 END) as Capacity
from fma0
where fma0.bldgcode = 'tst01'
group by fma0.bldgcode, fma0.floorcode
)tmp
order by bldgcode, floorcode
答案 1 :(得分:0)
另一种选择是按如下方式使用CTE(注意到目前为止的其他答案都给出了SUM(SUM(占用)+ SUM(容量)):
WITH CTE_SUMS ([bldgcode], [floorcode], [Occupancy], [Capacity])
AS (
SELECT
fma0.bldgcode AS [bldgcode],
fma0.floorcode AS [floorcode],
sum(fma0.occ) AS [Occupancy],
sum(CASE WHEN FMA0.SPACETYPE like 'A-OFF-%' OR
FMA0.SPACETYPE like 'A-WKS-%' THEN FMA0.CAPACITY
ELSE 0 END) AS [Capacity]
FROM fma0
WHERE fma0.bldgcode = 'tst01'
GROUP BY fma0.bldgcode, fma0.floorcode
)
SELECT [bldgcode], [floorcode], [Occupancy], [Capacity], ([Occupancy] / [Capacity]) AS [Sum]
FROM CTE_SUMS
这基本上会给你SUM(占用)/ SUM(容量)以及已经考虑的分组。
答案 2 :(得分:-2)
SELECT
bldgcode,
floorcode,
Occupancy,
Capacity ,
Occupancy+Capacity AS allsum
FROM(
select
fma0.bldgcode,
fma0.floorcode,
sum(fma0.occ) as Occupancy,
sum(CASE WHEN FMA0.SPACETYPE like 'A-OFF-%' OR
FMA0.SPACETYPE like 'A-WKS-%' THEN FMA0.CAPACITY
ELSE 0 END) as Capacity
from fma0
where fma0.bldgcode = 'tst01'
group by fma0.bldgcode, fma0.floorcode
)tmp
order by bldgcode, floorcode