获得计数总和

时间:2013-01-16 14:50:51

标签: sql-server

View获取前三列。我需要在视图中再添加一列(totalCount)来获取总计数:

CId CCId CCount  totalCount
1      a      3         6
1      a      3         6
1      b      3         6
1      c      3         6
2      b      2         6
2      b      2         6
2      a      2         6
2      a      2         6
3      v      1         6

如何将totalCount设为6?

(Cid的业务规则= 1 Ccount = 3 Cid = 2 Ccount = 2 Cid = 3 Ccount = 1因此totalCount = 3 + 2 + 1 = 6)

3 个答案:

答案 0 :(得分:1)

SELECT  a.CID, a.CCID, a.CCOUNT,
        b.TotalCount
FROM    Table1 a, (SELECT SUM(DISTINCT cCOunt) TotalCount 
                   FROM Table1) b

<强>更新

Andomar在评论中指出,已对查询进行了更新,

SELECT  a.CID, a.CCID, a.CCOUNT,
        b.TotalCount
FROM    Table1 a, 
(
  SELECT SUM(TotalCount) TotalCount
  FROM
  (
      SELECT MAX(cCOunt) TotalCount 
      FROM Table1
      GROUP BY CId
   ) c
) b

答案 1 :(得分:1)

使用此代码,我得到了预期的结果:

select CId
      ,CCId
      ,CCount
      ,(select SUM(a.tcount) 
          from (select distinct CId ,CCount as tcount
       from  dbo.Test) as a ) totalcount
from dbo.Test

答案 2 :(得分:0)

根据您的示例数据,我假设Cid只能有一个(可能是重复的)CCount值。在这种情况下,您可以使用maxgroup by选择一个随机的(sum):

select  sum(OneCCCount) as TotalCount
from    (
        select  max(CCount) as OneCCCount
        from    YourTable
        group by
                CId
        ) as SubQueryAlias