按表分组,然后将另一个表计数添加到第一个表分组计数中

时间:2019-04-18 09:28:39

标签: sql

我想按第一个表分组,然后将第二个和第三个表的结果与已分组的计数相加...但是要使用伪服务代码

select servicecode, Count(*) as count from servicerequest
    where To_Char(CREATEDATE,'YYYY') = 2018
    and status = 50
    group by servicecode

        union

    select Count(*) as count from CERTREQUEST
     WHERE to_char(REQDATE,'yyyy') = 2018
    and service = 1

        union

    select Count(*) as count from LTR
     WHERE to_char(REQDATE,'yyyy') = 2018
    and Service = 1

2 个答案:

答案 0 :(得分:1)

只需在其他两个查询中选择它即可:

select servicecode, Count(*) as count from servicerequest
    where To_Char(CREATEDATE,'YYYY') = 2018
    and status = 50
    group by servicecode

        union

    select 1, Count(*) as count from CERTREQUEST
     WHERE to_char(REQDATE,'yyyy') = 2018
    and service = 1

        union

    select 2, Count(*) as count from LTR
     WHERE to_char(REQDATE,'yyyy') = 2018
    and Service = 1

答案 1 :(得分:0)

使参数号相同,因为我假设servicecode是varchar,所以使用emty字符串,根据数据类型在此处放置值

select servicecode, Count(*) as count from servicerequest
    where To_Char(CREATEDATE,'YYYY') = 2018
    and status = 50
    group by servicecode

        union all

    select '', Count(*) as count from CERTREQUEST
     WHERE to_char(REQDATE,'yyyy') = 2018
    and service = 1

        union all

    select '',Count(*) as count from LTR
     WHERE to_char(REQDATE,'yyyy') = 2018
    and Service = 1

我更喜欢全部合并