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)
答案 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
值。在这种情况下,您可以使用max
和group by
选择一个随机的(sum
):
select sum(OneCCCount) as TotalCount
from (
select max(CCount) as OneCCCount
from YourTable
group by
CId
) as SubQueryAlias