【问题标题】:Data across multiple years.跨多年的数据。
【发布时间】:2017-01-16 14:42:45
【问题描述】:

我需要一次显示以下多年的结果。因此,与其在 2014 年、2015 年、最后 2016 年运行这份报告,我更愿意在三年内运行一次(@startDate 和 @endDate)。不确定汇总是否有效?还是分组集?用户想要比较多年的数据。谢谢!

select ct.srv_ct_label as service, count (distinct cln.cln_urn) as total
 from cw_domain dmn
inner join cw_service srv on srv.srv_dmn_fk=dmn.dmn_pk
inner join cw_client cln on cln.cln_pk=srv.srv_cln_fk
inner join cw_subservice sbs on sbs.sbs_pk=srv.srv_sbs_fk
inner join cw_service_category ct on ct.srv_ct_rpk=sbs.sbs_srv_ct_rfk
where
srv_ct_rpk in (
'001',
'002',
'004',
'025',
'040',
'003',
'026',
'017',
'016',
'034',
'041',
'042',
'018',
'029'
)
and srv.srv_date >=@startDate and srv.srv_date <=endDate
group by ct.srv_ct_label, srv_ct_rpk, srv.srv_date
order by
case srv_ct_rpk
when '001' then 1
when'040' then 2
when '003' then 3
when '025' then 4
when '002' then 5
when '004' then 6
when '041' then 7
when '026' then 8
when '017' then 9
when '034' then 10
when '042' then 11
when '018' then 12
when '029' then 13
end

【问题讨论】:

    标签: sql sql-server tsql grouping rollup


    【解决方案1】:

    根据需要在selectgroup byorder by 中为year(srv.srv_date) as srv_year 添加一列:

    select year(srv.srv_date) as srv_year, ct.srv_ct_label as service, count (distinct cln.cln_urn) as total
     from cw_domain dmn
    inner join cw_service srv on srv.srv_dmn_fk=dmn.dmn_pk
    inner join cw_client cln on cln.cln_pk=srv.srv_cln_fk
    inner join cw_subservice sbs on sbs.sbs_pk=srv.srv_sbs_fk
    inner join cw_service_category ct on ct.srv_ct_rpk=sbs.sbs_srv_ct_rfk
    where
    srv_ct_rpk in (
    '001',
    '002',
    '004',
    '025',
    '040',
    '003',
    '026',
    '017',
    '016',
    '034',
    '041',
    '042',
    '018',
    '029'
    )
    and srv.srv_date >=@startDate and srv.srv_date <=endDate
    group by year(srv.srv_date), ct.srv_ct_label, srv_ct_rpk, srv.srv_date
    order by year(srv.srv_date),
    case srv_ct_rpk
    when '001' then 1
    when'040' then 2
    when '003' then 3
    when '025' then 4
    when '002' then 5
    when '004' then 6
    when '041' then 7
    when '026' then 8
    when '017' then 9
    when '034' then 10
    when '042' then 11
    when '018' then 12
    when '029' then 13
    end
    

    【讨论】:

      【解决方案2】:

      您似乎想以水平方式比较和显示它们。 因此,我推荐使用selfjoin,如下所示。

      select * from
      (select ... 
      from tableA join tableB join ...
      on ...
      where srv.srv_date = 2014) as a
      JOIN
      (select ... 
      from tableA join tableB join ...
      on ...
      where srv.srv_date = 2015) as b ON ...
      JOIN
      (select ... 
      from tableA join tableB join ...
      on ...
      where srv.srv_date = 2016) as c ON ...
      

      【讨论】:

        猜你喜欢
        • 2021-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-22
        • 2016-04-28
        • 1970-01-01
        • 2020-08-22
        • 1970-01-01
        相关资源
        最近更新 更多