【问题标题】:SQL Server Adding a Where clause into a view?SQL Server 在视图中添加 Where 子句?
【发布时间】:2019-01-09 13:38:05
【问题描述】:

我有这样的看法:

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()) 子句,但不确定将其放置在何处。

【问题讨论】:

    标签: sql-server date where


    【解决方案1】:

    答案是这样的

    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
    

    ** 只是您视图名称的提示。给它起一个名字来表示年份过滤器

    【讨论】:

    • 感谢您的提示
    【解决方案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 CLAUSE就是这个顺序

    SELECT
    Columns
    FROM TABLEA 
    WHERE 
    GROUP BY
    ORDER BY
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 2014-02-14
      • 2021-08-09
      相关资源
      最近更新 更多