联盟在选择

时间:2017-11-01 06:50:07

标签: sql-server tsql sum union

这里我想在结尾显示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

1 个答案:

答案 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表示我们再次显示SUMcm.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)
            ,()
        )