SQL Query从左联接表返回True或False

时间:2016-04-20 10:55:34

标签: mysql

表ClientServices左连接到表客户

Table Customers

SysRef  FullName
1       ABC
2       RST
3       XYZ

Table Client Services

ClientSysRef  ServiceID
1             10
2             14
2             7
3             8

每个服务ID对应于所提供的特定服务。例如,ServiceID 7是IT,ServiceID 8是Accounts,Service ID 10是Marketing,ServiceID 14是HR。如果找到特定客户端的ServiceID,我需要找到返回True,否则返回false。必填结果;

SysRef  FullName  IT    Accounts    Marketing    HR
1       ABC       False False       True         False
2       RST       True  False       False        True
3       XYZ       False True        False        False

这可能与SQL有关吗?有人可以指导我吗?感谢

当前结果;

SysRef  FullName  IT    Accounts    Marketing    HR
1       ABC       False False       True         False
2       RST       True  False       False        False
2       RST       False False       False        True
3       XYZ       False True        False        False

2 个答案:

答案 0 :(得分:1)

是的,您可以使用Control Flow Functions:

SELECT 
    SysRef,
    IF(ServiceID = 7, 'TRUE', 'FALSE') as IT,
    ... #The same for the others

答案 1 :(得分:0)

select c.sysref,c.fullname,case when d.serviceID = 7 then 'TRUE' else 'FALSE' end as IT,
case when d.serviceID = 8 then 'TRUE' else 'FALSE' end as Accounts,
case when d.serviceID = 10 then 'TRUE' else 'FALSE' end as Marketing,
case when d.serviceID = 14 then 'TRUE' else 'FALSE' end as HR from customers c join client_services d on c.sysref = d.clientsysref;