选择中的多个组

时间:2016-01-15 13:16:35

标签: sql sql-server

它给了我11个结果

select min(e.UserId), e.Value from Table 
where UserId = 1 and EventTypeId = 3 and Value is not null 
group by e.Value

但如果我查询:

SELECT e.UserId, e.Value, count(UserId) as UserIdCount
  FROM [G3CR_Test].[dbo].[EventLog] as e
  where EventTypeId = 3 and Value is not null and UserId = 1
  group by e.UserId, e.Value
  order by e.UserId

它给出了结果

UserId  Value   UserIdCount

1       X1             1
1       X2             1
1       X3             12
1       X4             1
1       X5             5
1       X6             1
1       X7             1
1       X8             1
1       X9             12
1       X10             1
1       X11             1

因此,不是直接写入UserIdCount 11,而是将它们分开。 我知道它为什么会那样(see link here

但我想首先按Value和UserId对它们进行分组。怎么可能?

我希望结果是

UserId  Value   UserIdCount

1       X            11

1 个答案:

答案 0 :(得分:1)

在初始查询进行初步分组后,您正在查找行数,因此我们将原始查询转换为子查询,然后对其进行计数......

SELECT
    DerivedPreGrouped.UserId,
    COUNT(DerivedPreGrouped.UserIdCount) AS [Count]
FROM
    (
    SELECT 
        e.UserId, 
        e.Value, 
        count(UserId) as UserIdCount
    FROM 
        [G3CR_Test].[dbo].[EventLog] as e
    where 
        EventTypeId = 3 
        and 
        Value is not null 
        and UserId = 1
    group by 
        e.UserId 
        , e.Value
    /*
    order by 
        e.UserId
    --order by invalid in subquery
    */
    ) DerivedPreGrouped
GROUP BY
    DerivedPreGrouped.UserId
ORDER BY
    DerivedPreGrouped.UserId