使用查找表值作为列的SQL查询

使用查找表值作为列的SQL查询,sql,sql-server-2008,join,subquery,cross-reference,Sql,Sql Server 2008,Join,Subquery,Cross Reference,我有3个表:设备、服务、设备X服务 表设备有一个设备列表和与设备相关的字段,如序列号设备名称等 DeviceID | Device Name | SerialNumber 1 | iPhone | 2352532533 2 | iPad | 2345435435 3 | android | 2532532656 表服务是一个查找表,其中包含可在电子邮件、互联网、文本等设备上使用的服务列表 ServiceID | Serv

我有3个表:设备、服务、设备X服务

表设备有一个设备列表和与设备相关的字段,如序列号设备名称等

DeviceID | Device Name | SerialNumber 1 | iPhone | 2352532533 2 | iPad | 2345435435 3 | android | 2532532656 表服务是一个查找表,其中包含可在电子邮件、互联网、文本等设备上使用的服务列表

ServiceID | ServiceName 1 | email 2 | internet 3 | texting 表DeviceXService是一个交叉引用表,它有一条记录,将设备链接到服务以及这些设备的状态

比如说

DeviceID | ServiceID | Status -------------------------------------- 1(iPhone) | 1(email) | requested 2(ipad) | 2(internet) | Approved 1(iPhone) | 3(texting) | Approved 3(android) | 3(texting) | approved 我想做的是创建一个查询,该查询将返回devices表中的所有设备,但也为service表中存在的每种类型的服务创建一列,并将DeviceXService交叉引用表中每个设备的每个服务的状态作为一个表返回

例如:

Device ID | Device Name | Device Serial No | email | texting | internet -------------------------------------------------------------------------------- 1 | iphone | 2352532533 | requested| approved | null 2 | ipad | 2345435435 | null | null | approved 3 | android | 2532532656 | null | null | approved 注意:如果设备在DeviceXService交叉引用表中没有服务记录,则为null

如果我没有很好地解释这一点,我很抱歉,但这可能就是为什么我很难找到类似的例子。任何帮助都将不胜感激

如果服务表中的行数为常量且已知,则可以这样做:

select
 d.*,
 (select status from DeviceXService where Device_id=d.DeviceID and ServiceID=1) as email,
 (select status from DeviceXService where Device_id=d.DeviceID and ServiceID=2) as texting,
 (select status from DeviceXService where Device_id=d.DeviceID and ServiceID=3) as internet
from
 device d;
 id |  name   | serial | email | texting | internet 
----+---------+--------+-------+---------+----------
  1 | iphone  | 123    | req   | app     | 
  2 | ipad    | 234    |       |         | app
  3 | android | 345    |       |         | app
(3 rows)
结果如下所示:

select
 d.*,
 (select status from DeviceXService where Device_id=d.DeviceID and ServiceID=1) as email,
 (select status from DeviceXService where Device_id=d.DeviceID and ServiceID=2) as texting,
 (select status from DeviceXService where Device_id=d.DeviceID and ServiceID=3) as internet
from
 device d;
 id |  name   | serial | email | texting | internet 
----+---------+--------+-------+---------+----------
  1 | iphone  | 123    | req   | app     | 
  2 | ipad    | 234    |       |         | app
  3 | android | 345    |       |         | app
(3 rows)
如果您希望它是动态的,只需根据代码中服务表中的数据生成这样一个查询,然后对数据库运行它

我不认为通过sql查询将行转换为列是最好的方法,如果您可以在代码中做得更简单的话

编辑:


您可以查看或者,它们涉及的主题完全相同—动态SQL。

您使用的是哪种RDBMS?MySQL、SQL server、Postgress、Access、Oracle…?我使用的是MS SQL 2008。感谢您的回复。我想你给我指明了正确的方向。我确实希望列是动态的,因为新服务可以随时添加到表中。您能详细说明一下,基于代码中服务表的数据生成这样一个查询,然后对数据库运行它是什么意思吗?我的意思是,您可以查询服务表以获取所有行,然后构建第二个查询,该查询将包含您需要的所有列—它需要对服务表中的行进行循环,您将在其中添加以查询这些部分:从DeviceXService选择状态,其中Device_id=d.DeviceID和ServiceID=as,。另外,考虑一下这种语句的性能——对于每个设备,它需要查询N次DeviceXService表以获得列值。