我试图通过avg vacationleavehours和avg sickleaveHours获得第三列。
SELECT AVG(VacationHours) AS 'Vacation Hours', AVG(SickLeaveHours) AS 'Sick Leave Hours'
FROM HumanResources.employee
WHERE (YEAR(BirthDate) BETWEEN '1960' AND '1969')
GROUP BY BirthDate
UNION
SELECT AVG(VacationHours), AVG(SickLeaveHours)
FROM HumanResources.employee
WHERE YEAR(BirthDate) BETWEEN '1970' AND '1979'
GROUP BY BirthDate
UNION
SELECT AVG(VacationHours), AVG(SickLeaveHours)
FROM HumanResources.employee
WHERE YEAR(BirthDate) BETWEEN '1980' AND '1989'
GROUP BY BirthDate
OutPut
vacation sick
45 42
50 45
55 47
我得到平均假期和病假,但我想要第三栏,说明平均值属于哪一年。我试过小组,但它一年四季都给我。
我正在寻找这个输出。
vacation sick BirthDate
45 42 1960-1969
50 45 1970-1979
55 47 1980-1989
答案 0 :(得分:1)
无需过于花哨。您有三个单独的查询要加入,因此请明确指定每个查询的日期范围:
SELECT AVG(VacationHours) AS 'Vacation Hours', AVG(SickLeaveHours) AS 'Sick Leave Hours',
'1960-1969' AS BirthDate
FROM HumanResources.employee
WHERE (YEAR(BirthDate) BETWEEN '1960' AND '1969')
GROUP BY BirthDate
UNION
SELECT AVG(VacationHours), AVG(SickLeaveHours), '1970-1979'
FROM HumanResources.employee
WHERE YEAR(BirthDate) BETWEEN '1970' AND '1979'
GROUP BY BirthDate
UNION
SELECT AVG(VacationHours), AVG(SickLeaveHours), '1980-1989'
FROM HumanResources.employee
WHERE YEAR(BirthDate) BETWEEN '1980' AND '1989'
GROUP BY BirthDate
答案 1 :(得分:0)
SELECT
AVG(CASE WHEN (YEAR(BirthDate) BETWEEN '1960' AND '1969' THEN VacationHours ELSE 0 END)) AS 'Vacation Hours',
AVG(CASE WHEN (YEAR(BirthDate) BETWEEN '1960' AND '1969' THEN SickLeaveHours ELSE 0 END)) AS 'Sick Leave Hours',
'1960-1969' AS 'BirthDate'
FROM HumarResources.employee
UNION
SELECT
AVG(CASE WHEN (YEAR(BirthDate) BETWEEN '1970' AND '1979' THEN VacationHours ELSE 0 END)) AS 'Vacation Hours',
AVG(CASE WHEN (YEAR(BirthDate) BETWEEN '1970' AND '1979' THEN SickLeaveHours ELSE 0 END)) AS 'Sick Leave Hours',
'1970-1979' AS 'BirthDate'
FROM HumarResources.employee
SELECT
AVG(CASE WHEN (YEAR(BirthDate) BETWEEN '1980' AND '1989' THEN VacationHours ELSE 0 END)) AS 'Vacation Hours',
AVG(CASE WHEN (YEAR(BirthDate) BETWEEN '1980' AND '1989' THEN SickLeaveHours ELSE 0 END)) AS 'Sick Leave Hours',
'1980-1989' AS 'BirthDate'
FROM HumarResources.employee
你应该试试这个
答案 2 :(得分:0)
我认为你可以使用MIN,MAX和CONCAT,而不是如下:
SELECT AVG(VacationHours) AS 'Vacation Hours',
AVG(SickLeaveHours) AS 'Sick Leave Hours',
CONCAT(MIN(YEAR(BirthDate)), '-', MAX(YEAR(BirthDate))) AS BirthDate
FROM HumanResources.employee
WHERE (YEAR(BirthDate) BETWEEN '1960' AND '1969')
GROUP BY BirthDate
UNION
SELECT AVG(VacationHours),
AVG(SickLeaveHours),
CONCAT(MIN(YEAR(BirthDate)), '-', MAX(YEAR(BirthDate))) AS BirthDate
FROM HumanResources.employee
WHERE YEAR(BirthDate) BETWEEN '1970' AND '1979'
GROUP BY BirthDate
UNION
SELECT AVG(VacationHours),
AVG(SickLeaveHours),
CONCAT(MIN(YEAR(BirthDate)), '-', MAX(YEAR(BirthDate))) AS BirthDate
FROM HumanResources.employee
WHERE YEAR(BirthDate) BETWEEN '1980' AND '1989'
GROUP BY BirthDate