-1

I have 3 tables: Device, Service, DeviceXService

Table (Device) has a list of devices and fields associated to the devices such as serial number device name etc.

DeviceID | Device Name | SerialNumber
1        | iPhone      | 2352532533
2        | iPad        | 2345435435
3        | android     | 2532532656

Table (Service) is a lookup table that has a list of services that can be used on devices such as email, internet, texting etc.

ServiceID  | ServiceName
1          | email
2          | internet
3          | texting

Table (DeviceXService) is a cross-reference table that has a record linking devices to services and the status of those devices.

For example.

DeviceID    | ServiceID   | Status
--------------------------------------
1(iPhone)   | 1(email)    | requested
2(ipad)     | 2(internet) | Approved
1(iPhone)   | 3(texting)  | Approved
3(android)  | 3(texting)  | approved

What I would like to do is create a query that would return all the devices FROM the Devices table, but also create a column for each type of service that exists FROM the Service table and return the status of each service for each device FROM the DeviceXService cross-reference table as one table.

example:

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

Note: null is if the device doesn't have a record for the service in the DeviceXService cross-reference table

I apologize if I'm not explaining this very well but that may be why I'm having such a hard time trying to find an example of something similar. Any help would be greatly appreciated!

4

1 回答 1

0

如果表中的行数Service是恒定的且已知的,您可以这样做:

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。

于 2014-03-12T16:44:57.330 回答