根据来自不同表的关系使用数据创建SQL视图

时间:2018-08-03 13:06:25

标签: sql sql-server

我对SQL还是很陌生,我正在尝试在Microsoft SSMS中创建SQL视图。我提出了一些我很满意的观点,但是与此同时,我遇到了一些问题。我做了一个简化的例子,试图解释我要做什么。

比方说,我有3张桌子,其中一张列出了人们,第二张列出了颜色,第三张列出了人们喜欢哪种颜色之间的关系。

Three tables

我现在想要做的是创建一个视图,该视图显示每人一行,说明该人是否喜欢红色。

View result

SELECT 
    Person.Id, Person.Name, Color.Colorname, 
    CASE 
       WHEN ColorId = 4 THEN 'YES' 
       ELSE 'NO' 
    END AS 'Likes Red'
FROM 
    Person 
INNER JOIN 
    Color ON Person.Id = Color.Id 
INNER JOIN 
    PersonColorRelations ON Person.Id = PersonColorRelations.PersonId

2 个答案:

答案 0 :(得分:0)

我会使用exists

select *, (case when exists (select 1 
                             from PersonColorRelations pr 
                             where pr.PersonId = p.id and 
                                   pr.colorid = 4
                            )
                then 'Yes' else 'No'
           end) LikesRed
from Person p;

编辑:有关更多信息,您可以进行条件聚合:

select p.id, p.Name, 
       isnull(max(case when pr.colorid = 1 then 'Yes' end), 'No') as LikesBlack,
       isnull(max(case when pr.colorid = 2 then 'Yes' end), 'No') as LikesBlue,
       isnull(max(case when pr.colorid = 4 then 'Yes' end), 'No') as LikesRed,
       . . . 
from person p inner join
     PersonColorRelations pr
     on pr.PersonId = p.id
group by p.id, p.Name;

答案 1 :(得分:0)

尝试一下

http://sqlfiddle.com/#!9/71213f/18

select p.id,p.name,
case when max(c.colorname) is not null 
  then 'Yes' else 'No'
  end as LikesRed
from
PERSON p
left join PERSONCOLORRELATIONS pc
on p.id=pc.NAMEID
left join COLOR c
on pc.colorid=c.id
and c.colorname='RED'
group by p.id,p.name;

如果要派生另一列(例如LikesBlue),则只需在倒数第二行更改颜色名称。