如何在2个查询的结果与组之间执行减法?
第一个查询返回所有房屋的数量,让我们说可以出租的房屋,而第二个返回已经出租的房屋。
SELECT
(SELECT COUNT(*) FROM ... GroupBy ...)
- (SELECT COUNT(*) FROM ... WHERE ...group by) AS Difference
首先查询结果
count() column2 column3
3 studio newYork
6 studio pekin
3 apprtment pekin
5 house london
1 house lagos
第二个查询结果
count() column2 column3
2 studio newYork
我希望根据第二个
的结果更新第一个查询count() column2 column3
1 studio newYork
6 studio pekin
3 apprtment pekin
5 house london
1 house lagos
答案 0 :(得分:3)
只需使用条件聚合:
SELECT COUNT(*) -
SUM(CASE WHEN <some_condition> THEN 1 ELSE 0 END) AS some_count,
column2,
column3
FROM yourTable
GROUP BY column2, column3
此处<some_condition>
是原始第二次计数查询的WHERE
子句中出现的内容。
答案 1 :(得分:1)
如何在2个查询的结果之间执行减法 一群人?
你很接近你拥有的东西。然而,有一些变化可以使这项工作更容易:
Count(*)
语句中添加别名。同样,这将使它们更容易使用。如果此图片展示了您要找的内容:
然后我相信这个查询会帮助你:
SELECT op.ApartmentType,
op.ApartmentLocation,
op.TotalOwned,
ISNULL(tp.TotalOccupied, 0) AS [TotalOccupied],
op.TotalOwned - ISNULL(tp.TotalOccupied,0) AS [TotalVacant]
FROM
(
SELECT *,
COUNT(*) as TotalOwned
FROM SO_SubtractionQuestion.OwnedProperties
GROUP BY ApartmentType, ApartmentLocation
) AS op
LEFT JOIN
(
SELECT *,
COUNT(*) as TotalOccupied
FROM [SO_SubtractionQuestion].[OccupiedProperties]
GROUP BY ApartmentType, ApartmentLocation
) AS tp
ON op.ApartmentType = tp.ApartmentType
AND op.ApartmentLocation = tp.ApartmentLocation
我将此查询设置为类似于您自己的查询:它有一个带有两个子查询的select语句,子查询在分组查询上有一个Count(*)
。我还在上面添加了我建议的内容:
op
(拥有的属性),而我的第二个子查询的别名是tp
(属性)。Count(*)
个语句有别名。在我的外部查询中,我可以加入ApartmentType 和 ApartmentLocation(请查看下面的示例表/数据设置)。这将创建一个结合在ApartmentType和ApartmentLocation上的结果集,该结果集还包含有多少自有属性(来自第一个子查询的Count(*)
)以及有多少被占用属性(来自第二个Count(*)
子查询)。在这一点上,因为我有所有别名,我能够做简单的减法,看看op.TotalOwned - ISNULL(tp.TotalOccupied,0) AS [TotalVacant]
有多少属性是空的。
我也在使用ISNULL
来纠正空值。如果我没有这个,对于没有来自第二个子查询的匹配的行,减法的结果也将为null。
要为自己设置示例,以下是要运行的查询:
出于组织目的
CREATE SCHEMA SO_SubtractionQuestion;
CREATE TABLE SO_SubtractionQuestion.OwnedProperties
(
ApartmentType varchar(20),
ApartmentLocation varchar(20)
);
CREATE TABLE SO_SubtractionQuestion.OccupiedProperties
(
ApartmentType varchar(20),
ApartmentLocation varchar(20)
);
INSERT INTO [SO_SubtractionQuestion].[OwnedProperties] VALUES ('Studio', 'New York'), ('Studio', 'New York'), ('Studio', 'New York'), ('House', 'New York'), ('House', 'Madison');
INSERT INTO [SO_SubtractionQuestion].[OccupiedProperties] VALUES ('Studio', 'New York'), ('Studio', 'New York');
答案 2 :(得分:0)
Select Column2, Column3, Count(*)-(Select Count(*)
From Table2
Where Table1.Column2=Table2.Column2 and Table1.Column3=Table2.Column3)
From Table1
Group by Column2, Column3