查询返回同一列的多个值?

时间:2019-09-30 17:35:55

标签: sql sql-server join

我正在运行一个简单的查询,并要求两次从同一表返回同一列。由于某些原因,该列返回两个不同的结果。有人可以解释一下原因,并告诉我如何让查询两次返回一致的结果吗?

这是我正在运行的代码:

SELECT WIN1.SERVERNAME,
       WIN1.APPLICATION AS 'App 1',
       WIN1.STATUS      AS 'Status 1',
       WIN1.IPADDRESS   AS 'WIN1 IP',
       WIN2.APPLICATION AS 'App 2',
       WIN2.STATUS      AS 'Status 2',
       WIN2.IPADDRESS   AS 'WIN2 IP'
FROM   SERVER.WINDOWS WIN1,
       SERVER.WINDOWS WIN2
WHERE  WIN1.IPADDRESS IS NOT NULL
       AND WIN2.IPADDRESS IS NOT NULL
       AND WIN1.SERVERNAME LIKE '%SERVER NAME%'
       AND WIN1.STATUS LIKE '%line%'
       AND WIN2.STATUS LIKE '%line%'
       AND WIN2.APPLICATION LIKE '%APPLICATION NAME%' 

谢谢。

1 个答案:

答案 0 :(得分:0)

通过向查询中添加同一张表两次类似于执行完全外部联接,即是将表与其自身联接,where子句使事情更难弄清,只需调用没有任何过滤器的查询即可理解查询两次调用同一张表的效果。

从这一点上来说,您应该能够完成所需的工作。

SELECT WIN1.SERVERNAME,
   WIN1.APPLICATION AS 'App 1',
   WIN1.STATUS      AS 'Status 1',
   WIN1.IPADDRESS   AS 'WIN1 IP',
   WIN2.APPLICATION AS 'App 2',
   WIN2.STATUS      AS 'Status 2',
   WIN2.IPADDRESS   AS 'WIN2 IP'
FROM   SERVER.WINDOWS WIN1,
   SERVER.WINDOWS WIN2

OR

Select * FROM   
   SERVER.WINDOWS WIN1,
   SERVER.WINDOWS WIN2