0

这应该很简单。我正在使用 SSMS 2008,试图得到一列的总和。问题是我目前在这一列上分组并且还使用 HAVING 语句。如何获得总记录数 > 1 的总和?这是我目前的 T-SQL 逻辑:

select count(*) as consumer_count from #consumer_initiations
group by consumer
having count(1) > 1

但是这个数据看起来像:

consumer_count 
----------------
2
2
4
3
...
4

5 回答 5

3

包起来?

SELECT SUM(consumer_count)
FROM (
    select count(*) as consumer_count from #consumer_initiations
    group by consumer
    having count(1) > 1
) AS whatever
于 2011-09-27T20:28:59.607 回答
1

使用嵌套查询:

select sum(consumer_count)
FROM (

    select count(*) as consumer_count from #consumer_initiations
    group by consumer
    having count(1) > 1
) as child
于 2011-09-27T20:29:10.190 回答
1
select sum(t.consumer_count)
    from (select count(*) as consumer_count 
              from #consumer_initiations
              group by consumer
              having count(1) > 1) t
于 2011-09-27T20:29:50.830 回答
0

尝试:

select sum(t.consumer_count) from
(
    select count(*) as consumer_count from #consumer_initiations
    group by consumer
    having count(1) > 1
) t

这将为您提供原始查询返回的记录总和。这些类型的查询称为嵌套查询。

于 2011-09-27T20:31:26.893 回答
0

除了包装在另一个查询中,你可以使用这个:

SELECT COUNT(*) AS consumer_count 
FROM #consumer_initiations AS a
WHERE EXISTS
      ( SELECT *
        FROM #consumer_initiations AS b
        WHERE b.consumer = a.consumer
          AND b.PK <> a.PK                -- the Primary Key of the table
      )
于 2011-09-27T20:41:33.883 回答