SQL ANY作为函数而不是运算符

时间:2019-07-19 07:22:44

标签: sql sql-server

我需要计算符合特定条件的用户。为此,我需要连接一些表并检查是否有任何分组组合符合条件。 我现在实现的方法是,通过嵌套选择对原始匹配项进行计数,然后对具有至少一个结果的行进行计数。

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

让我讨厌的是,嵌套选择中的计数仅用于检查是否存在。但是,由于SQL中的ANY只是运算符,因此我无法想到一种更干净的方法来重写它。

查询按原样返回正确的结果。 我想知道是否有任何方法可以重写它,从而避免产生仅用于检查存在条件的中间结果?

样本输入User.csv Group.csv UserGroup.csv

预期结果:483、272、121

2 个答案:

答案 0 :(得分:2)

可能可以简化该查询。

我认为可以避免UserId上的组。
通过对用户标识使用不同的条件计数。

那么就不需要子查询了。

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;

答案 1 :(得分:0)

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