简体   繁体   中英

Format MySQL using CONCAT

Thanks to some help I have a MySQL query that starts on 2014-10-10 and fines the amount of holidays in 12 months period eg 2014-10-10 to 2015-10-09 then 2015-10-10 to 2016-10-09

SELECT 
    e.name AS Employee,
    CEIL(DATEDIFF(h.date, e.startdate)/365) as Year,
    count(h.date) as Holidays_Taken
FROM employees AS e
LEFT JOIN holidays_taken AS h ON e.id = h.empid
WHERE e.id = 1
GROUP BY Year

With a result

+----------+------+---------------+
| Employee | Year | Holidays_Taken|
+----------+------+---------------+
| Jon      | 1    | 5             |
+----------+------+---------------+
| Jon      | 2    | 1             |
+----------+------+---------------+

Is it possible to have the year show 2014-10-10 to 2015-10-09 instead of year 1 then 2015-10-10 to 2016-10-09 for year 2

Here's my SQL FIDDLE

Thanks

Not sure I've got your goal, but here is my approach:

http://sqlfiddle.com/#!9/371a7/14

SELECT 
    e.name AS Employee,
    @year := CEIL(DATEDIFF(h.date, e.startdate)/365) AS Year,
    CONCAT(DATE_ADD(e.startdate, INTERVAL @year-1 YEAR),' - ',DATE_ADD(e.startdate, INTERVAL @year YEAR)),
    COUNT(h.date) AS Holidays_Taken,
    SUM(h.hours) AS Hours
FROM employees AS e
LEFT JOIN holidays_taken AS h ON e.id = h.empid
WHERE e.id = 1 
GROUP BY Year

I would create the CONCAT in this manner:

SELECT 
    e.name AS Employee,
    CONCAT(
        CEIL(DATEDIFF(h.date, e.startdate)/365), 
        ' (',
        DATE_ADD(e.startdate, INTERVAL FLOOR(DATEDIFF(h.date, e.startdate)/365) YEAR), ' to ',        
        DATE_ADD(e.startdate, INTERVAL CEIL(DATEDIFF(h.date, e.startdate)/365) YEAR),
        ')'
        ) as Year,
    COUNT(h.date) AS Holidays_Taken,
    SUM(h.hours) AS Hours
FROM employees AS e
LEFT JOIN holidays_taken AS h ON e.id = h.empid
WHERE e.id = 1
GROUP BY Year

DEMO: SQL FIDDLE

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