SQL - 将多个列添加到VIEW

时间:2015-09-17 14:44:04

标签: sql join left-join sql-view

我创建了一个视图,并且工作正常(如下面的视图“A”所示)。 现在我必须将另一个表中的列连接到视图。我的工作如下图“B”所示。 有谁知道正确的语法是什么?

(使用METRIC_NUMBER = METRIC_ID_OLD加入LK_METRICS 从公制表中添加[小标题],[标题],[演示]和[SLS]列)

查看 A

CREATE VIEW [dbo].[V_PS_DA]
AS  WITH
today AS
(   SELECT * 
    FROM dbo.LK_NET_WORK_DAYS 
    WHERE [DATE] = CAST(GETDATE() AS DATE)
)
SELECT 
  p.*,
  hrs.DATE_ORDINAL      ENTER_HRSC_ORDINAL,
  strt.DATE_ORDINAL     START_DATE_ORDINAL,
  ndt.DATE_ORDINAL      END_DATE_ORDINAL,
  today.DATE_ORDINAL    TODAY_ORDINAL,
FROM dbo.PS_DA p
LEFT JOIN dbo.LK_NET_WORK_DAYS hrs
  ON p.ENTER_HRSC = hrs.[DATE]
LEFT JOIN dbo.LK_NET_WORK_DAYS strt
  ON p.START_DATE = strt.[DATE]
LEFT JOIN dbo.LK_NET_WORK_DAYS ndt
  ON p.END_DATE = ndt.[DATE]
CROSS JOIN today;  
GO

查看 B

CREATE VIEW [dbo].[V_PS_DA]
AS WITH
today AS
(   SELECT * 
    FROM dbo.LK_NET_WORK_DAYS -- This contains the date data needed
    WHERE [DATE] = CAST(GETDATE() AS DATE)
)
SELECT 
  p.*,
  hrs.DATE_ORDINAL      ENTER_HRSC_ORDINAL,
  strt.DATE_ORDINAL     START_DATE_ORDINAL,
  ndt.DATE_ORDINAL      END_DATE_ORDINAL,
  today.DATE_ORDINAL    TODAY_ORDINAL,
  kst.[Small Title] Small_Title,
  kt.[Title]    Title,
  kd.[Demonstration]  Demonstration,
  ks.SLS    SLS

FROM dbo.PS_DA p, dbo.LK_METRICS k
LEFT JOIN dbo.LK_NET_WORK_DAYS hrs
  ON p.ENTER_HRSC = hrs.[DATE]
LEFT JOIN dbo.LK_NET_WORK_DAYS strt
  ON p.START_DATE = strt.[DATE]
LEFT JOIN dbo.LK_NET_WORK_DAYS ndt
  ON p.END_DATE = ndt.[DATE]
CROSS JOIN today,
LEFT JOIN dbo.LK_METRICS k
  ON k.METRIC_ID_OLD = METRIC_NUMBER

1 个答案:

答案 0 :(得分:1)

你非常接近。你只是在那里发生了一些额外的事情。取出SELECT P FROM Project P WHERE :currentUser MEMBER OF P.assignedUsers 行逗号后的位:

FROM ..

唯一的另一件事是指定哪个表CREATE VIEW [dbo].[V_PS_DA] AS WITH today AS ( SELECT * FROM dbo.LK_NET_WORK_DAYS -- This contains the date data needed WHERE [DATE] = CAST(GETDATE() AS DATE) ) SELECT p.*, hrs.DATE_ORDINAL ENTER_HRSC_ORDINAL, strt.DATE_ORDINAL START_DATE_ORDINAL, ndt.DATE_ORDINAL END_DATE_ORDINAL, today.DATE_ORDINAL TODAY_ORDINAL, kst.[Small Title] Small_Title, kt.[Title] Title, kd.[Demonstration] Demonstration, ks.SLS SLS FROM dbo.PS_DA p LEFT JOIN dbo.LK_NET_WORK_DAYS hrs ON p.ENTER_HRSC = hrs.[DATE] LEFT JOIN dbo.LK_NET_WORK_DAYS strt ON p.START_DATE = strt.[DATE] LEFT JOIN dbo.LK_NET_WORK_DAYS ndt ON p.END_DATE = ndt.[DATE] CROSS JOIN today, LEFT JOIN dbo.LK_METRICS k ON k.METRIC_ID_OLD = METRIC_NUMBER 来自哪个。那是METRIC_NUMBER吗?由于您可能只有一个包含字段p.METRIC_NUMBER的表,但是使用SQL,最好尽可能明确地表示它不会产生任何影响。

最后,您可以在SELECT语句中使用METRIC_NUMBER表中的字段,如:

K