通过查询求和组的结果

时间:2016-12-19 05:14:05

标签: sql-server

我在SQL Server中运行以下查询,返回计数和城市:

JBHL/40/16-17

我得到以下结果:

SELECT 
    COUNT(*), city 
FROM 
    address 
WHERE
    address1 LIKE '%[0-9]%' 
    AND phone1 LIKE '%[0-9]%'
GROUP BY
    city
HAVING 
    COUNT(*) > 250
ORDER BY
    COUNT(*) DESC

如何编写查询以获取计数结果的总和(上例中的1232 + 345?)

我已经尝试了子查询,但由于该组似乎导致了一些错误。我不熟悉SQL,并为一个糟糕的问题道歉。

4 个答案:

答案 0 :(得分:4)

试试这个:

select sum(c)
from (
    select COUNT(*) c
    from address
    where address1 like '%[0-9]%'
        and phone1 like '%[0-9]%'
    group by city
    having count(*) > 250
    );

答案 1 :(得分:3)

您可以定义CTE然后使用它:

WITH cte AS (
    SELECT city, COUNT(*) AS total
    FROM address
    WHERE address1 LIKE '%[0-9]%' AND
          phone1 LIKE '%[0-9]%'
    GROUP BY city
    HAVING COUNT(*) > 250
)

SELECT t.city,
       t.total,
       (SELECT SUM(total) FROM cte) AS grand_total
FROM cte t
ORDER BY t.total DESC

如果您只想要总计,请使用以下查询:

SELECT SUM(total) AS grand_total
FROM cte

答案 2 :(得分:1)

这是使用SUM Over()窗口聚合函数

的另一种方法
SELECT city,
       Count(*) AS total,
       Sum(Count(*))OVER() grand_total
FROM   address
WHERE  address1 LIKE '%[0-9]%'
       AND phone1 LIKE '%[0-9]%'
GROUP  BY city
HAVING Count(*) > 250 

答案 3 :(得分:1)

您可以使用GROUP的ROLLUP,例如:

    ;WITH address(address1,phone1,city) AS
    (
        SELECT '1','2','Atlanta' UNION ALL 
        SELECT '2','2','Atlanta' UNION ALL 
        SELECT '3','2','Atlanta' UNION ALL 
        SELECT '4','2','Atlanta' UNION ALL 
        SELECT '5','2','Chicago' UNION ALL 
        SELECT '6','0','Chicago' UNION ALL 
        SELECT '7','0','Chicago'
    )
    SELECT COUNT(*), ISNULL(city,'Summary') FROM address where
    address1 LIKE '%[0-9]%'
    and phone1 LIKE '%[0-9]%'
    group by city WITH ROLLUP
    HAVING count(*) > 2
    order BY CASE WHEN city IS NULL THEN 1 ELSE 0 END , COUNT(*) DESC

----------- -------
4           Atlanta
3           Chicago
7           Summary