结合sql查询

时间:2013-06-10 20:14:48

标签: sql sql-server

我是T SQL的新手,我有两个查询需要根据常用列值组合它们。 这两个查询都可以单独运行。

第一个查询是

SELECT t_senderTable.nameFull AS "senderName", t_recieverTable.recieverName AS "recieverName" 
FROM ((dbo.t_senderTable AS t_senderTable
     INNER JOIN t_senderTable AS t_senderTable ON (t_senderTable.Kd = mapTable.senderID))
     INNER JOIN t_recieverTable AS t_recieverTabler ON (recieverTable.Id = mapTable.recieverID )

第二个查询是

SELECT t_license AS "License", t_coName AS "Company Name" 
FROM (dbo.t_license AS t_license
     INNER JOIN dbo. t_coName ON ( t_coName.id = t_license.senderID ))
WHERE
(
  t_license.check < '2' )

基本上我需要结合两个查询,以便使用两个查询之间通用的senderID,我得到senderName,recieverName和coName的输出结果 senderID是一对多关系。 从这篇文章得到了想法,但无法让它工作Combining SQL Server Queries 任何想法如何去做?谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用UNION(删除重复的行)或UNION ALL(返回所有行)。要使其工作,您的列需要在两个查询中匹配。

答案 1 :(得分:0)

您可以将两个查询作为子查询,在两个子查询的select子句中包含senderId字段,并加入这些值。我想你要求的是:

SELECT q1.senderName
     , q1.recieverName
     , q2."Company Name"
(
SELECT t_senderTable.nameFull AS "senderName", t_recieverTable.recieverName AS "recieverName" 
     , t_senderTable.Id
FROM ((dbo.t_senderTable AS t_senderTable
     INNER JOIN t_senderTable AS t_senderTable ON (t_senderTable.Kd = mapTable.senderID))
     INNER JOIN t_recieverTable AS t_recieverTabler ON (recieverTable.Id = mapTable.recieverID )
) q1
INNER JOIN (
SELECT t_license AS "License", t_coName AS "Company Name" 
     , t_license.senderID
FROM (dbo.t_license AS t_license
     INNER JOIN dbo. t_coName ON ( t_coName.id = t_license.senderID ))
WHERE
(
  t_license.check < '2' )
) q2
  ON q1.Id = q2.senderId