计算前六个月和过去六个月的FYear

时间:2016-07-26 13:36:36

标签: sql sql-server tsql

我需要计算一年中前六个月和本财政年度最后六个月都有服务的所有患者。这就是我想出的,但不确定它是否会完全干净。

var xml = @"<inserted>  
    <row>    
        <CODI_AVERIA>21</CODI_AVERIA>    
        <NUMERO_LINIA>2</NUMERO_LINIA>    
        <DIA>2016-07-17T00:00:00</DIA>    
        <HORA>1899-12-30T10:26:15.790</HORA>    
        <CODI_USUARI>1</CODI_USUARI>    
        <ACCIO>0</ACCIO>    
        <CODI_PSEUDO>-1</CODI_PSEUDO>  
    </row>
</inserted>";

var xdoc = XDocument.Parse(xml);

var items = xdoc.Element("inserted").Elements("row").Select(n => new
{
    Codi_averia = n.Element("CODI_AVERIA").Value,
    Numero_linia = n.Element("NUMERO_LINIA").Value,
    Accio = n.Element("ACCIO").Value

}).ToList();

本报告正在研究的是跟上治疗的客户数量。为了让我们的客户群得到关注&#39;他们必须每年两次去看医生:一次是在上半年,一次是在下半年。

2 个答案:

答案 0 :(得分:0)

如果您想要计算每个客户端有多少服务,您需要使用count函数。

select HalfOfYear
     , NumOfPatients = count(Client)
from (select  
         cln_urn as Client
        ,case when datepart(q,srv_date) in (1,2) then 'FirstHalf'   
              when datepart(q,srv_date) in (3,4) then 'SecondHalf'  
              end as HalfOfYear
     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.srv_date >= '03/01/2015'
      and srv.srv_date <= '02/29/2016'
      and srv_ct_rpk = '002'

      ) as x
group by HalfOfYear

答案 1 :(得分:0)

这应该可以解决问题。只需将@from和@thru替换为您的日期。

WITH sd AS
(
    SELECT
        DISTINCT
        cln.cln_urn, 
        CASE
            WHEN srv.srv_date < DATEADD(MONTH, 6, @from) THEN 1
            WHEN srv.srv_date >= DATEADD(MONTH, 6, @from) THEN 2
            END AS 'half'
    FROM
        cw_domain dmn
        INNER JOIN cw_service AS 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.srv_date >= @from
        AND srv.srv_date <= @thru
        AND srv_ct_rpk = '002'
)

SELECT
    COUNT(cln.cln_urn)
FROM
    sd AS fh
    JOIN sd AS sh
        ON fh.cln_urn = sh.cln_urn
WHERE
    fh.half = 1
    AND sh.half = 2