将数据从两个选择查询添加到一个表中,这些查询针对来自两个不同表的不同列数

时间:2017-12-12 10:16:27

标签: sql sql-server

我有两个选择查询在每个查询中具有不同的列数,具有不同的where条件。我想将从两个选择查询收集的数据添加到一个表中。我已经看到了做“UNION”的方法,但是在这种情况下,两个查询中的列需要在数量上相同,我如何将两个查询中的数据添加到单个表中。我的疑问如下:

Select 
Village_ID,
Village_Name,
RSP_ID,
Other_Loan_Source,
Informal_Money_Lender_Loans
from(
Select DISTINCT SETTLEMENT_ID as Village_ID,
SETTLEMENT_NAME as Village_Name,
RSP_ID,
(SELECT COUNT(*) FROM PscData where SETTLEMENT_ID  = T.SETTLEMENT_ID 
AND TAKEN_LOAN = 6 )as Other_Loan_Source,
(SELECT COUNT(*) FROM PscData where SETTLEMENT_ID  = T.SETTLEMENT_ID 
AND TAKEN_LOAN = 5 )as Informal_Money_Lender_Loans

FROM PscData as T

)tmp

,第二个问题是:

SELECT
        SUM(CASE WHEN  t2.SEX = 1
        THEN 1 ELSE 0 END) AS Total_Males,

        SUM(CASE WHEN  t2.SEX = 2
        THEN 1 ELSE 0 END) AS Total_Females,

        SUM(CASE WHEN   t2.MARITAL_STATUS = 1
        THEN 1 ELSE 0 END) AS Total_Married,
        t1.SETTLEMENT_ID 
FROM PScData t1 
INNER JOIN PscMemberData t2
    ON t2._PARENT_AURI = t1.URI
GROUP BY
    t1.SETTLEMENT_ID
HAVING COUNT(*) > 1;

如何将这些结果合并到一个表中。

2 个答案:

答案 0 :(得分:0)

您可以先使用union创建一个表,只使用两个表中存在的字段。然后将此表连接到原始表以添加其余字段。

with cte as (
select Village_ID as village_settlement_id
  from #tmp_1
 union 
select SETTLEMENT_ID as village_settlement_id
  from #tmp_2
)
select * 
     , #tmp_1.Village_ID
     , #tmp_1.Village_Name
     , #tmp_1.RSP_ID
     , #tmp_1.Other_Loan_Source
     , #tmp_1.Informal_Money_Lender_Loans
     , #tmp_2.Total_Males
     , #tmp_2.Total_Females
     , #tmp_2.Total_Married
  from cte 
  left join #tmp_1 on cte.village_settlement_id = #tmp_1.Village_ID  
  left join #tmp_2 on cte.village_settlement_id = #tmp_1.SETTLEMENT_ID

答案 1 :(得分:0)

为什么不直接在第二个表中添加一个虚拟列?

SELECT
        SUM(CASE WHEN  t2.SEX = 1
        THEN 1 ELSE 0 END) AS Total_Males,

        SUM(CASE WHEN  t2.SEX = 2
        THEN 1 ELSE 0 END) AS Total_Females,

        SUM(CASE WHEN   t2.MARITAL_STATUS = 1
        THEN 1 ELSE 0 END) AS Total_Married,
        t1.SETTLEMENT_ID ,
        '' Informal_Money_Lender_Loans
FROM PScData t1