聚合和总计

时间:2015-01-23 00:10:09

标签: sql sql-server tsql

SELECT  Region ,
        flag ,
        Name,
        COUNT(ID) AS 'CountWithFlag'
FROM    Table
GROUP BY flag

此查询给出了以下结果。我按旗分组,我可以根据旗帜获得英语/非英语的计数。我还希望显示与计数相邻的英语和非英语总计数

输出:

Region Flag  Name     CountWithFlag
a      0     English        100
b      1     Non-English    200 
c      0     English        100
d      1     Non-English    200

期望的输出:

Region Flag  Name     CountWithFlag  Total
a      0     English        100       200
b      1     Non-English    200       400
c      0     English        100       200
d      1     Non-English    200       400

我该怎么做?我想通过标志应用group by特定计数。但我也想在同一个查询中得到总计数!

关于我如何做到这一点的任何意见?

3 个答案:

答案 0 :(得分:0)

另一种方式是这样的:

;
WITH    agg1
            AS (
                SELECT  region,
                        flag,
                        name,
                        COUNT(id) AS 'CountWithFlag'
                FROM    [dbo].[t2]
                GROUP BY region,
                        flag,
                        name
                ),
        agg2
            AS (
                SELECT  [name],
                        COUNT(id) AS CountByName
                FROM    [dbo].[t2]
                GROUP BY [name]
                )
    SELECT  [agg1].[region],
            [agg1].[flag],
            [agg1].[name],
            [agg1].[CountWithFlag],
            [agg2].[CountByName]
    FROM    [agg1]
            INNER JOIN [agg2]
                ON [agg2].[name] = [agg1].[name]

答案 1 :(得分:0)

试试这个

  ;
    WITH    cte
              AS ( SELECT DISTINCT
                            Region ,
                            flag ,
                            Name ,
                            COUNT(ID) OVER ( PARTITION BY flag, Region, Name ) AS [CountWithFlag]
                   FROM     [Table]
                 )
        SELECT  Region ,
                flag ,
                Name ,
                SUM([CountWithFlag]) OVER ( PARTITION BY Name ) AS Total
        FROM    cte

答案 2 :(得分:0)

如果您想避免使用窗口功能,可以这样做:

SELECT 
  Region,
  flag,
  Name,
  COUNT(ID) AS CountWithFlag,
  (select count(ID) from Table as tbl1 where tbl1.Name=tbl.Name) AS Total
from Table as tbl
group by Region, flag, Name

但我认为窗口聚合应该更快。

如果您想使用窗口聚合,请执行以下操作:

select 
  Region,
  flag,
  Name,
  CountWithFlag,
  sum(CountWithFlag) over(partition by Name) as Total
from (
  SELECT 
    Region,
    flag,
    Name,
    COUNT(ID) AS CountWithFlag
  from Table as tbl
  group by Region, flag, Name
) as tbl