SQL ANY作为函数而不是运算符
我需要计算符合特定条件的用户数。为此,我需要连接一些表,并检查是否有任何分组组合符合条件。 我现在实现的方法是使用一个嵌套的select来计算原始匹配,然后计算至少有一个结果的行SQL ANY作为函数而不是运算符,sql,sql-server,Sql,Sql Server,我需要计算符合特定条件的用户数。为此,我需要连接一些表,并检查是否有任何分组组合符合条件。 我现在实现的方法是使用一个嵌套的select来计算原始匹配,然后计算至少有一个结果的行 SELECT COUNT(case when NestedCount1 > 0 then 1 else null end) as Count1, COUNT(case when NestedCount2 > 0 then 1 else null end) as Count2, COU
SELECT
COUNT(case when NestedCount1 > 0 then 1 else null end) as Count1,
COUNT(case when NestedCount2 > 0 then 1 else null end) as Count2,
COUNT(case when NestedCount3 > 0 then 1 else null end) as Count3
FROM
(SELECT
COUNT(case when Type = 1 then 1 else null end) as NestedCount1,
COUNT(case when Type = 2 then 1 else null end) as NestedCount2,
COUNT(case when Type = 2 AND Condition = 1 then 1 else null end) as NestedCount3
FROM [User]
LEFT JOIN [UserGroup] ON [User].Id = [UserGroup].UserId
LEFT JOIN [Group] ON [UserGroup].GroupId = [Group].Id
GROUP BY [User].Id) nested
令我恼火的是,嵌套select的计数仅用于检查是否存在。然而,由于SQL中的任何函数都只是一个操作符,我想不出一个更简洁的方法来重写它
查询按原样返回正确的结果。
我想知道是否有任何方法可以重写它,以避免产生只用于检查存在条件的中间结果
样本输入
预期结果:483272121有可能简化该查询 我认为用户ID上的组是可以避免的。
通过对用户id使用不同的条件计数 那么就不需要子查询了
SELECT
COUNT(DISTINCT case when [User].[Type] = 1 then [User].Id end) as Count1,
COUNT(DISTINCT case when [User].[Type] = 2 then [User].Id end) as Count2,
COUNT(DISTINCT case when [User].[Type] = 2 AND Condition = 1 then [User].Id end) as Count3
FROM [User]
LEFT JOIN [UserGroup] ON [UserGroup].UserId = [User].Id
LEFT JOIN [Group] ON [Group].Id = [UserGroup].GroupId;
如果你能提供样本数据和预期结果,那就太好了。我可能需要重新表述我的问题。我的问题是正确的。但是我对它的外观并不满意,我希望有更好的方法。嘿,穆尼什,试着解释一下为什么这段代码可以解决OP的问题。只有代码的答案没有那么有建设性。
SELECT
SUM(case when NestedCount1 > 0 then 1 else 0 end) as Count1,
SUM(case when NestedCount2 > 0 then 1 else 0 end) as Count2,
SUM(case when NestedCount3 > 0 then 1 else 0 end) as Count3
FROM
(
SELECT
[User].Id,
COUNT(case when Type = 1 then 1 else 0 end) as NestedCount1,
COUNT(case when Type = 2 then 1 else 0 end) as NestedCount2,
COUNT(case when Type = 2 AND Condition = 1 then 1 else 0 end) as NestedCount3
FROM [User]
LEFT JOIN [UserGroup] ON [UserGroup].UserId = [User].Id
LEFT JOIN [Group] ON [Group].Id = [UserGroup].GroupId
GROUP BY [User].Id
) nested