简体   繁体   中英

Getting sum of months to show as years in SQL or SSRS

I have a SQL query that gets the total number of days an employee was active with the company. Some employees can come an go several times as the seasons change so the query takes that into account. An example is below:

EmpNum     HireDate     TermDate     Days     Years     Months
 1018     2015-02-23   2015-04-09     45       0          1
 1018     2015-12-04   2016-07-08    217       0          7
 1018     2017-04-10   2018-01-08    273       0          9

So for this employee, they have 17 months active days. However, I want to show in an SSRS report the sum of the months and I don't want to show it as 17 months but as 1 year 5 months.

This seems to get you the right answer:

-- Setup
DECLARE @emp_activity TABLE
(
    emp_num INT NOT NULL,
    hire_date DATETIME NOT NULL,
    term_date DATETIME NOT NULL
);

INSERT INTO @emp_activity 
    (emp_num, hire_date, term_date)
VALUES 
    (1018, '2015-02-23','2015-04-09'),
    (1018, '2015-12-04','2016-07-08'),
    (1018, '2017-04-10','2018-01-08');

;WITH cte AS 
(
    SELECT 
        emp_num, 
        hire_date, 
        term_date,
        DATEDIFF(DAY, hire_date, term_date) AS days
    FROM @emp_activity
)
SELECT 
    cte.emp_num, 
    cte.hire_date, 
    cte.term_date, 
    days, 
    FLOOR(cte.days/364.25) years, 
    FLOOR(cte.days/30.5) months
INTO #temp
FROM cte;

SELECT t.emp_num, t.hire_date, t.term_date, t.days, t.months, t.years
FROM #temp t;

-- This is really the answer to your question
SELECT t.emp_num,   
    FLOOR(SUM(t.days)/364.25) years, 
    FLOOR((SUM(t.days) - FLOOR(SUM(t.days)/364.25)*364.25)/30.5) months
FROM #temp t
GROUP BY t.emp_num

-- Cleanup
DROP TABLE #temp;

You can do it simply with algebra. Years are Months/12 without rest, remaining months are total months - years * 12.

Otherwise you might try using TimeSpan, although I don't know how much of its functionality exists in SSRS:

http://alexandermlharris.azurewebsites.net/index.php/2012/08/31/ssrs-report-timespan-formatting/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM