根据日期的数据

时间:2018-01-09 05:04:08

标签: sql-server sql-server-2008 date

我有这样的数据

compnay         employee    service_start_Date  service_end_Date   service_status
abc company     david       01/01/2017          1/1/1900            in_service
abc comapny     john        12/02/2016          1/1/1900            in_service
defcompany      abc_1       05/12/2011          12/02/2017          regisned
ghgcompany      rock        02/11/2009          04/03/2017          terminated
abc company1    david1      01/01/2017          1/1/1900            in_service
abc company     david2      01/01/2017          1/1/1900            in_service
abc company2    david3      01/01/2017          1/1/1900            in_service
abc company     david4      01/01/2015          1/1/2017            in_service
abc company2    david5      01/01/2017          1/1/1900            in_service

......还有很多这样的数据

这里当员工没有辞职/终止/过期时,默认日期设置如此1/1/1900 当员工辞职/ termindate / expired时,service_end_date被标记为所以我想要数据 比如根据月份和年份加入和离开的员工数量 像这样

如果我选择参数第1个月和2017年,那么这个节目就像这样

company          joiners  leavers
abc company         3        1
abc company1        3        0

当我选择像2011年和2011年那样的时候,这就像这样显示

company    joiners  leavers
defcompany  1        0

我试过这个

select  e.company,count(e.EmployeeIndex) joiners,count(e.EmployeeIndex) leavers
            from    emp_table e 
            where                   

                     service_end_Date between 
                    convert(datetime,rtrim(convert(char,@FromDate,101)),101) 
                     and  convert(datetime,rtrim(convert(char,@ToDate,101)),101) 

                     and service_start_Date between 
                    convert(datetime,rtrim(convert(char,@FromDate,101)),101) 
                     and  convert(datetime,rtrim(convert(char,@ToDate,101)),101) 
        group by e.company

    this query did not show correct data..

2 个答案:

答案 0 :(得分:0)

您当前的查询对于加入者和离开者都计算两次相同的事情。您需要将检查移动到这些列的选择区域。这是基本的想法

select  e.company,
    SUM(case when service_start_date between @FromDate and @ToDate then 1 else 0 end) as joiners
    , SUM(case when service_end_date between @FromDate and @ToDAte then 1 else 0 end) as leavers

from    emp_table e 
        where                   
            service_end_Date between @FromDate and @ToDate
        OR --not AND
            service_start_Date between @FromDate and @ToDate
group by e.company

你可以将整个底部的where子句关闭,它仍然可以工作,但即使两个数字都为零(这可能是想要或不想),它也会返回所有公司。

答案 1 :(得分:0)

您可以使用以下查询来实现此目的:

SELECT *
 FROM (
  SELECT employee, compnay
  ,Case when year(service_end_Date) = 1900 then
  'joiners'
  else 
  'leavers' end as Company_Year
  FROM [emp_table] 
  -- where  year(service_start_Date) = 2011  and month(service_start_Date) = 5
 ) as s
 PIVOT
 (
  count(employee)
  FOR [Company_Year] IN (joiners,leavers)
 )AS pvt;