我在下面有这个查询。但我认为有更好的方式来写这个。两者之间的唯一区别是VacancyType检查
IF @VacancyType = ''
SELECT COUNT(a.[ApplicationID]) [AppCount], YEAR(a.[DateCreated]) [Year], MONTH(a.[DateCreated]) [Month]
FROM [Application] a
INNER JOIN [Vacancy] v ON v.VacancyID = a.VacancyID
INNER JOIN Staff s ON s.StaffID = v.StaffID
WHERE
v.[DateCreated] >= @DateFrom AND v.[DateCreated] <= @DateTo
AND (@OfficeID = 0 Or s.OfficeID = @OfficeID)
AND v.VacancyType IN (SELECT TypeID FROM VacancyType)
GROUP BY YEAR(a.[DateCreated]), MONTH(a.[DateCreated])
ORDER BY YEAR(a.[DateCreated]), MONTH(a.[DateCreated])
ELSE
SELECT COUNT(a.[ApplicationID]) [AppCount], YEAR(a.[DateCreated]) [Year], MONTH(a.[DateCreated]) [Month]
FROM [Application] a
INNER JOIN [Vacancy] v ON v.VacancyID = a.VacancyID
INNER JOIN Staff s ON s.StaffID = v.StaffID
WHERE
v.[DateCreated] >= @DateFrom AND v.[DateCreated] <= @DateTo
AND (@OfficeID = 0 Or s.OfficeID = @OfficeID)
AND v.VacancyType = @VacancyType
GROUP BY YEAR(a.[DateCreated]), MONTH(a.[DateCreated])
ORDER BY YEAR(a.[DateCreated]), MONTH(a.[DateCreated])
答案 0 :(得分:0)
假设唯一区别在于v.VacancyType
条件,那么您可以使用OR
SELECT COUNT(a.[ApplicationID]) [AppCount], YEAR(a.[DateCreated]) [Year], MONTH(a.[DateCreated]) [Month]
FROM [Application] a
INNER JOIN [Vacancy] v ON v.VacancyID = a.VacancyID
INNER JOIN Staff s ON s.StaffID = v.StaffID
WHERE
v.[DateCreated] >= @DateFrom AND v.[DateCreated] <= @DateTo
AND (@OfficeID = 0 Or s.OfficeID = @OfficeID)
AND
(
(@VacancyType = '' AND v.VacancyType IN (SELECT TypeID FROM VacancyType)) OR
(@VacancyType <> '' AND v.VacancyType = @VacancyType)
)
GROUP BY YEAR(a.[DateCreated]), MONTH(a.[DateCreated])
ORDER BY YEAR(a.[DateCreated]), MONTH(a.[DateCreated])
答案 1 :(得分:0)
试试这个
SELECT COUNT(a.[ApplicationID]) [AppCount], YEAR(a.[DateCreated]) [Year], MONTH(a.[DateCreated]) [Month]
FROM [Application] a
INNER JOIN [Vacancy] v ON v.VacancyID = a.VacancyID
INNER JOIN Staff s ON s.StaffID = v.StaffID
WHERE
v.[DateCreated] >= @DateFrom AND v.[DateCreated] <= @DateTo
AND (@OfficeID = 0 Or s.OfficeID = @OfficeID)
AND ((@VacancyType = '' AND v.VacancyType IN (SELECT TypeID FROM VacancyType))
OR (v.VacancyType = @VacancyType)
)
GROUP BY YEAR(a.[DateCreated]), MONTH(a.[DateCreated])
ORDER BY YEAR(a.[DateCreated]), MONTH(a.[DateCreated])