我有这个观点:
ALTER VIEW [dbo].[vw_HoursTakenPerEmployee] AS
SELECT e.[EmployeeID],
COALESCE(SUM(hrf.[HoursTaken]), 0) AS HoursTaken
FROM [dbo].[Employee] e LEFT JOIN
[dbo].[HolidayRequestForm] hrf
ON e.[EmployeeID] = hrf.[EmployeeID]
GROUP BY e.[EmployeeID];
GO
holidayRequestform表看起来像这样。
EmployeeID | HoursTaken | YearRequested | MonthRequested |
------------+----------------+ ---------------+----------------+
1 | 8 | 2018 |06
1 | 16 | 2019 |01
2 | 8 | 2019 |01
3 | 8 | 2018 |01
当我选择视图时,结果如下:
EmployeeID|HoursTaken
----------+----------
1 |24
2 |8
3 |8
但是,我只想查看“计算当年(2019)”的小时数,同时仍保留前几年的记录。
我尝试在视图中插入WHERE YearRequested = YEAR(GETDATE())
子句,但不确定将其放置在何处。
答案 0 :(得分:3)
答案是
ALTER VIEW [dbo].[vw_HoursTakenPerEmployee] AS
SELECT e.[EmployeeID],
COALESCE(SUM(hrf.[HoursTaken]), 0) AS HoursTaken
FROM [dbo].[Employee] e LEFT JOIN
[dbo].[HolidayRequestForm] hrf
ON e.[EmployeeID] = hrf.[EmployeeID]
WHERE hrf.YearRequested = YEAR(GETDATE())
GROUP BY e.[EmployeeID];
GO
**只是您视图名称的提示。给它指定一个表示年份过滤器的名称
答案 1 :(得分:2)
ALTER VIEW [dbo].[vw_HoursTakenPerEmployee] AS
SELECT e.[EmployeeID],
COALESCE(SUM(hrf.[HoursTaken]), 0) AS HoursTaken
FROM [dbo].[Employee] e LEFT JOIN
[dbo].[HolidayRequestForm] hrf
ON e.[EmployeeID] = hrf.[EmployeeID]
WHERE YearRequested = YEAR(GETDATE())
GROUP BY e.[EmployeeID];
GO
-SQL中的SELECT子句按此顺序
SELECT
Columns
FROM TABLEA
WHERE
GROUP BY
ORDER BY