在SQL中创建非重复视图

时间:2017-06-08 09:41:49

标签: sql sql-server

我有两张桌子

  1. 开发

    • Developer_Id
    • 姓名
    • 手机号码
    • 电子邮件地址
    • 角色
    • 已分配给
  2. 作业表

    • JOB_ID
    • 作业名称
    • 作业说明
    • 创建者
    • 创建日期
    • 截止日期
    • 状态
  3. 我想查看JobList表,但它应该包括:

    • Developers.Full Name
    • Developers.Team
    • Developers.Role
    • Developers.Assigned To

    我创建了一个视图,但它返回了重复的值,如下所示:

    enter image description here

    有什么办法可以在一行中查看JobList表,但是包含了Developers表中的多个行,就像这样

    enter image description here

    这是我使用的代码

    创建表格:

    CREATE TABLE [dbo].[Developers] (
    [Developer_Id]     INT          NOT NULL,
    [Full Name]        VARCHAR (50) NULL,
    [Cellphone number] VARCHAR (50) NULL,
    [Email address]    VARCHAR (50) NULL,
    [Team]             VARCHAR (50) NULL,
    [Role]             VARCHAR (50) NULL, 
    [Assigned To] INT NULL, 
    CONSTRAINT [PK_Developers] PRIMARY KEY ([Developer_Id])
    );
    
    CREATE TABLE [dbo].[JobList] (
    [Job_Id]                 INT           NOT NULL,
    [Assignment Name]        VARCHAR (50)  NULL,
    [Assignment Description] VARCHAR (MAX) NULL,
    [Created By]             VARCHAR (50)  NULL,
    [Date Created]           DATE          NULL,
    [Due Date]               DATE          NULL, 
    [Status] VARCHAR(50) NULL, 
    CONSTRAINT [PK_JobList] PRIMARY KEY ([Job_Id])
    );
    

    创建视图

    CREATE VIEW [dbo].AssignedJobs
    AS SELECT JobList.[Assignment Name], JobList.[Assignment Description], JobList.[Due Date], JobList.[Status],Developers.[Full Name], Developers.[Role]
    from JobList
    inner join Developers
    on JobList.Job_Id = Developers.[Assigned To]
    

1 个答案:

答案 0 :(得分:0)

CREATE VIEW [dbo].AssignedJobs
AS SELECT JobList.[Assignment Name], JobList.[Assignment Description], 
JobList.[Due Date], JobList.[Status],Developers.[Full Name], Developers.[Role]
from JobList
inner join Developers
on JobList.Job_Id = Developers.[Assigned To]
group by JobList.[Assigment Name], JobList.[Assignment Description], JobList.[Due Date], JobList[Status], string_agg(Developers.[Full Name], ' ') as [Full Name], string_agg (Developers.Role, ' ') as Role

如果您不在SQL Server 2017 / Azure上,请使用以下内容:Agg with Stuff and XML FOR PATH