我在sql server中有一个员工数据源,我需要从中检索下面任一标准属于当天的员工列表
每位员工记录都有上述信息。基于这些条件,我需要在查询中连接一个字符串,如
我是编写SQL查询和新手的新手我试过这个。
select CONCAT(given_name,' ',sur_name) as name,
photo_link,birth_date,join_date,wedding_date
FROM emp_db where (DATEPART(dd,birth_date) = DATEPART(dd,getdate())
OR DATEPART(dd,join_date) = DATEPART(dd,getdate())
OR DATEPART(dd,wedding_date) = DATEPART(dd,getdate()))
AND status = 'employed'
ORDER BY Day(birth_date), Day(join_date), Day(wedding_date)"
有人可以为此提出一个好的解决方案吗?
答案 0 :(得分:1)
我认为你需要一个UNION。这与您要求的略有不同,因为它将为同一名员工提供多条记录,当且仅当他们在同一天庆祝多个活动时。像这样:
(
SELECT *, birth_date AS celebration_date, CONCAT('Happy birthday, ',given_name,' ',sur_name) AS celebration_message,
FROM emp_db WHERE DATEPART(dd,birth_date) = DATEPART(dd,getdate()) AND DATEPART(mm,birth_date) = DATEPART(mm,getdate())
) UNION (
SELECT *, wedding_date AS celebration_date, CONCAT('Happy anniversary, ',given_name,' ',sur_name) AS celebration_message,
FROM emp_db WHERE DATEPART(dd,wedding_date) = DATEPART(dd,getdate()) AND DATEPART(mm,wedding_date) = DATEPART(mm,getdate())
) UNION (
SELECT *, join_date AS celebration_date, CONCAT('Happy work anniversary, ',given_name,' ',sur_name) AS celebration_message,
FROM emp_db WHERE DATEPART(dd,join_date) = DATEPART(dd,getdate()) AND DATEPART(mm,join_date) = DATEPART(mm,getdate())
)
答案 1 :(得分:0)
请尝试
select case
when
( convert(varchar(10),ondate,103) = convert(varchar(10),getdate(),103 ) and CelebrateType='Birthday' )
then ('Happy Bithday '+ UserName )
when ( convert(varchar(10),ondate,103) = convert(varchar(10),getdate(),103 ) and CelebrateType='Anniversary ' )
then ('Happy Aniversary '+ UserName )
when ( convert(varchar(10),ondate,103) = convert(varchar(10),getdate(),103 ) and CelebrateType='Joining' )
then ('Happy joining '+ UserName )
end as Congretecolumnn
from TableName
where convert(varchar(10),ondate,103)= convert(varchar(10),getdate(),103)
答案 2 :(得分:0)
您的查询将返回正确的记录,但您不知道哪种情况属实 也就是说,你不知道他们是否因为他们的生日而在你的结果中,或者因为他们的周年纪念日......,
您可以查看每个结果日期,看看哪些是“点击”,或者您可以查询。
我认为你想使用dayofyear,而不是datelist(' dd')返回的月份,我想你也可以使用datepart(' dy' )
SELECT CONCAT(given_name,' ',sur_name) AS name, photo_link,
IF ( DAYOFYEAR(birth_date) = DAYOFYEAR(getdate()),'Birthday',NULL) AS birthday
IF ( DAYOFYEAR(join_date) = DAYOFYEAR(getdate()),'Joined',NULL) AS joined,
IF ( DAYOFYEAR(wedding_date) = DAYOFYEAR(getdate()), 'Wedding', NULL) AS wedding,
FROM emp_db WHERE ( DAYOFYEAR(birth_date) = DAYOFYEAR(getdate())
OR ( DAYOFYEAR(join_date) = DAYOFYEAR(getdate())
OR ( DAYOFYEAR(wedding_date) = DAYOFYEAR(getdate())
AND (status = 'employed')
ORDER BY Day(birth_date), Day(join_date), Day(wedding_date)
通常情况是循环查询结果并根据需要显示每一行。
还要考虑员工可以在同一天加入/结婚/出生的情况。
while ($row = $result->fetch_assoc()){
if ($row['birthday']) $txt .= 'Happy Birthday, '.$row['name']."\n";
if ($row['joined']) $txt .= 'Happy Work Anniversary, '.$row['name']."\n";
if ($row['wedding']) $txt .= 'Happy Wedding Anniversary, '.$row['name']."\n";
}