我想用给定的参数值执行两个不同的mysql查询。
这是我的疑问:
select Gender, count(EmployeeId) as NoOfEmployees
from people_HR.PEOPLE_HR
where EmploymentType = 'INTERNSHIP' and ((StartDate < '2006-07-01' AND EmployeeStatus = 'Active') OR (EmployeeStatus = 'Left' AND '2006-07-01' <= FinalDayofEmployment AND StartDate < '2006-07-01' )) and Gender<>'' group by Gender
此就业类型和日期将被指定为参数。如果EmploymentType ='Total',我需要为整个表运行查询。如何通过mysql查询实现这一目标?
注意:下面的代码作为我需要实现的伪代码。
if (EmploymentType = 'Total')
select Gender, count(EmployeeId) as NoOfEmployees
from people_HR.PEOPLE_HR
where ((StartDate < '2006-07-01' AND EmployeeStatus = 'Active') OR (EmployeeStatus = 'Left' AND '2006-07-01' <= FinalDayofEmployment AND StartDate < '2006-07-01' )) and Gender<>'' group by Gender
else
select Gender, count(EmployeeId) as NoOfEmployees
from people_HR.PEOPLE_HR
where EmploymentType = 'INTERNSHIP' and ((StartDate < '2006-07-01' AND EmployeeStatus = 'Active') OR (EmployeeStatus = 'Left' AND '2006-07-01' <= FinalDayofEmployment AND StartDate < '2006-07-01' )) and Gender<>''group by Gender
对此表示高度赞赏的任何帮助。
注意:这不是存储过程。因此不能直接使用“IF”,我需要通过“select if”来实现。
答案 0 :(得分:2)
IF (@EmploymentType = 'Total') THEN
select Gender, count(EmployeeId) as NoOfEmployees
from people_HR.PEOPLE_HR
where ((StartDate < '2006-07-01' AND EmployeeStatus = 'Active') OR (EmployeeStatus = 'Left' AND '2006-07-01' <= FinalDayofEmployment AND StartDate < '2006-07-01' )) and Gender<>'' group by Gender
ELSE
select Gender, count(EmployeeId) as NoOfEmployees
from people_HR.PEOPLE_HR
where EmploymentType = 'INTERNSHIP' and ((StartDate < '2006-07-01' AND EmployeeStatus = 'Active') OR (EmployeeStatus = 'Left' AND '2006-07-01' <= FinalDayofEmployment AND StartDate < '2006-07-01' )) and Gender<>''group by Gender
END IF
顺便说一下,你只能在存储过程或函数中使用if语句。
答案 1 :(得分:1)
您可以在此方案中使用CASE语句。这将适用于SQL查询。
select Gender, count(EmployeeId) as NoOfEmployees
from people_HR.PEOPLE_HR
where
CASE WHEN @EmploymentType = 'TOTAL' THEN
EmploymentType<>''
ELSE
EmploymentType=@EmploymentType
END
and ((StartDate < '2006-07-01' AND EmployeeStatus = 'Active') OR (EmployeeStatus = 'Left' AND '2006-07-01' <= FinalDayofEmployment AND StartDate < '2006-07-01' )) and Gender<>''group by Gender
答案 2 :(得分:0)
IF (@EmploymentType = 'Total')
BEGIN
select Gender, count(EmployeeId) as NoOfEmployees
from people_HR.PEOPLE_HR
where ((StartDate < '2006-07-01' AND EmployeeStatus = 'Active') OR (EmployeeStatus = 'Left' AND '2006-07-01' <= FinalDayofEmployment AND StartDate < '2006-07-01' )) and Gender<>'' group by Gender
END
ELSE
BEGIN
select Gender, count(EmployeeId) as NoOfEmployees
from people_HR.PEOPLE_HR
where EmploymentType = 'INTERNSHIP' and ((StartDate < '2006-07-01' AND EmployeeStatus = 'Active') OR (EmployeeStatus = 'Left' AND '2006-07-01' <= FinalDayofEmployment AND StartDate < '2006-07-01' )) and Gender<>''group by Gender
END