这里我想在结尾显示im.eindex
的计数。所以,为此,我使用union all
,但结果显示每条记录总数。
select
'' Field1,
'' Field2,
'Comp' GField1,
ltrim(rtrim(cm.CName)) CName,
count(im.eindex) Emp
From Log l,
IMaster im,
cmaste cm
where cm.cindex=im.cindex
and im.iindex=sms.iindex
and im.Month = 10
and im.year = 2017
and cm.type
group by cm.CName
union all
select
'' Field1,
'' Field2,
'Comp' GField1,
‘total’ CName,
sum(im.eindex) Emp
From Log l,
IMaster im,
cmaste cm
where cm.cindex=im.cindex
and im.iindex=sms.iindex
and im.Month = 10
and im.year = 2017
and cm.type
group by cm.CName
以上查询的输出为
Field1 Field2 GField1 CName Employees
ABC COM 91
XYZ COMP 15
Total 7759562
Total 21211214
答案 0 :(得分:0)
删除上一个group by
语句,因为我们要显示所有CName
的总数:
select
'' Field1,
'' Field2,
'Comp' GField1,
ltrim(rtrim(cm.CName)) CName,
count(im.eindex) Emp
From Log l,
IMaster im,
cmaste cm
where cm.cindex=im.cindex
and im.iindex=sms.iindex
and im.Month = 10
and im.year = 2017
and cm.type
group by cm.CName
union all
select
'' Field1,
'' Field2,
'Comp' GField1,
‘total’ CName,
count(im.eindex) Emp
From Log l,
IMaster im,
cmaste cm
where cm.cindex=im.cindex
and im.iindex=sms.iindex
and im.Month = 10
and im.year = 2017
and cm.type
在第二个group by
中设置SELECT
表示我们再次显示SUM
每cm.Cname
。
你甚至可以简化这个:
select
'' Field1,
'' Field2,
'Comp' GField1,
ISNULL(ltrim(rtrim(cm.CName)), 'Total') CName,
count(im.eindex) Emp
From Log l,
IMaster im,
cmaste cm
where cm.cindex=im.cindex
and im.iindex=sms.iindex
and im.Month = 10
and im.year = 2017
and cm.type
group by GROUPING SETS
(
(cm.CName)
,()
)