我在报告查询中使用以下SQL,我必须列出给定时间范围内的所有生日和纪念日。有没有更好的方法来避免UNION和SELECT - DISTINCT? 我已将此更改为使用UNION ALL,因为数据已经是不同的。
请注意,我们可以在同一时间段内举行纪念日和生日。
SELECT
gpms.[birthdate] AS [Date],
'Birthday' AS [Event],
gpms.[name] AS [Name],
gpms.[email] AS [Email],
gpms.[address] AS [Address],
FROM PERSONDETAILS gpms
JOIN @selectedpersons sgf ON sgf.[account] = gpms.[account]
WHERE DATEADD(year,DATEDIFF(YEAR, birthdate, @p_StartDate),birthdate) BETWEEN @p_StartDate AND @p_endDate
OR DATEADD(year,DATEDIFF(YEAR, birthdate, @p_endDate ),birthdate) BETWEEN @p_StartDate AND @p_endDate
UNION
SELECT
gpms.[birthdate] AS [Date],
'Birthday' AS [Event],
gpms.[name] AS [Name],
gpms.[email] AS [Email],
gpms.[address] AS [Address],
FROM PERSONDETAILS gpms
JOIN @selectedpersons sgf ON sgf.[account] = gpms.[account]
WHERE DATEADD(year,DATEDIFF(YEAR, Anniversary, @p_StartDate),Anniversary) BETWEEN @p_StartDate AND @p_endDate
OR DATEADD(year,DATEDIFF(YEAR, Anniversary, @p_endDate ),Anniversary) BETWEEN @p_StartDate AND @p_endDate
答案 0 :(得分:1)
试试这个:
SELECT
gpms.[birthdate] AS [Date],
'Birthday' AS [Event],
gpms.[name] AS [Name],
gpms.[email] AS [Email],
gpms.[address] AS [Address],
FROM PERSONDETAILS gpms
JOIN @selectedpersons sgf ON sgf.[account] = gpms.[account]
WHERE DATEADD(year,DATEDIFF(YEAR, birthdate, @p_StartDate),birthdate) BETWEEN @p_StartDate AND @p_endDate
OR DATEADD(year,DATEDIFF(YEAR, birthdate, @p_endDate),birthdate) BETWEEN @p_StartDate AND @p_endDate
OR DATEADD(year,DATEDIFF(YEAR, Anniversary, @p_StartDate),Anniversary) BETWEEN @p_StartDate AND @p_endDate
OR DATEADD(year,DATEDIFF(YEAR, Anniversary, @p_endDate),Anniversary) BETWEEN @p_StartDate AND @p_endDate