SQL - 多次选择列

时间:2014-06-18 03:20:38

标签: sql postgresql

我有3张桌子:

系统的系统

  

WorkstationID
  WorkstationName
  制造商
  OS

SoftwareInfo

  

WorkstationID
  SoftwareID

SoftwareList

  

SoftwareID
  SoftwareName
  SoftwareVersion

每个workstationID都有大约20个SoftwareID行(Reader,Flash,Java等)我希望输出看起来像这样:

WorkstationID | OS | Manufacturer| Reader Version | Flash Version | Java Version
Desktop01     | W7 | Lenovo      | 11.0.7         | 14.X          | 8.X

我无法弄清楚如何多次查询SoftwareList并过滤每个查询,以便它只返回相对于当前WorkstationID的SoftwareVersion。

这是我到目前为止的代码,它不会执行:

select 
  systeminfo.WorkstationName, 
  systeminfo.OS, 
  systeminfo.Manufacturer,
  (Select SoftwareList.SoftwareVersion 
   from systeminfo 
        join softwareinfo on systeminfo.workstationid = softwareInfo.workstationID 
        JOIN SoftwareList on softwareinfo.softwareid = softwarelist.softwareid 
   where SoftwareName = 'Reader' 
         and softwareinfo.workstationid = systeminfo.workstationid) as "Reader" 
from 
  systeminfo 
  join softwareinfo on systeminfo.workstationid = softwareInfo.workstationID 
  JOIN SoftwareList on softwareinfo.softwareid = softwarelist.softwareid

1 个答案:

答案 0 :(得分:0)

在这里采取一些猜测,FILEVERSION是SoftwareVersion。情况并不重要(我不认为,如果确实如此,那么我需要更新这个)。此外,这些是外部联接,因此,如果列不存在,例如,如果您缺少“Flash”版本,您仍将获得一行。如果不需要,请将“左连接”更改为“加入”。那么如果查询中存在所有软件,您将只获得元组。我不知道这是否有意义。对不起,我没试过这个。希望它有所帮助。

select
    s.WorkstationName,
    s.OS,
    s.Manufacturer,
    sr.softwareversion as "Reader",
    sf.softwareversion as "Flash"
  from
    systeminfo s
left join
    softwareinfo sor on (sor.workstationid = s.workstationid)
left join
    softwarelist sr on (sr.softwareid = sor.softwareid and sr.softwarename = 'Reader')
left join
    softwareinfo sof on (sof.workstationid = s.workstationid)
left join
    softwarelist sf on (sf.softwareid = sof.softwareid and sf.softwarename = 'Flash')