合并来自多个表的数据 SQL 服务器

时间:2021-05-06 12:20:49

标签: sql sql-server tsql

您好,我在数据库 CustomerPaymentRefund 中有 3 个表。结构如下:

客户表:

<头>
客户 ID 注意事项
1
2 你好
3 gg
4

付款表:

<头>
pmtId custId PmtNotes
10 1 kk
11 2 pp
12 3 NULL
15 4 dd

退款表:

<头>
refId custId refNotes
33 1 ww
34 2 毫米
35 3 jj
65 2 ii

预期结果:

<头>
客户 ID 注意事项 col1
3 gg 1
3 JJ 3

col1 = 1:因为这个数据来自 Customer 表。

col1 = 3:因为这个数据来自Refund表。

我想要这种基于客户 ID 的结果,我发现了类似的问题,但我找不到最相关的解决方案。 任何帮助将不胜感激,因为我是 SQL 服务器的初学者。

3 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望从不同的表中选择带有注释的客户以及数据所属表的指示。我只考虑了非空注释的行。请检查。

首先,我将笔记列不为空的三个表中的所有行合并,并添加了一个额外的列来指示该行来自哪个表。

架构和插入语句:

 create table Customer (CustId   int, Notes  varchar(50));          
 insert into Customer 
 values
 (1        , 'hi'     ),           
 (2        , 'hello'  ),            
 (3        , 'gg'     ),            
 (4        , 'hh'     );            
      
 create table Payment (pmtId int, custId int ,PmtNotes varchar(50));         
 insert into Payment  values
 (10    ,1     , 'kk'),       
 (11    ,2     , 'pp'),               
 (12    ,3     , NULL),             
 (15    ,4     , 'dd');               
 
 create table Refund (refId int, custId int, refNotes varchar(50));
 insert into Refund values
 (33    ,1      ,  'ww'),
 (34    ,2      ,  'mm'), 
 (35    ,3      ,  'jj'),
 (65    ,2      ,  'ii');

查询:

 select * from 
 (
     select custid, notes, 1 Col1 from customer where notes is not null
     union all
     select custid, PmtNotes, 2 Col1 from Payment where PmtNotes is not null
     union all
     select custid, refNotes, 3 Col1 from Refund where refNotes is not null
 )t where custid=3

输出:

<头>
custid 注释 Col1
3 gg 1
3 jj 3

dbhere

答案 1 :(得分:0)

这应该有效。

 SELECT * FROM Customer
    LEFT JOIN payment
    ON customer.CustId = Payment.custId
    LEFT JOIN Refund
    ON customer.CustId = Refund.CustId

SELECT * FROM Customer
   LEFT JOIN payment
   ON customer.CustId = Payment.custId
   LEFT JOIN Refund
   ON customer.CustId = Refund.CustId
WHERE Customer.CustId = 2 

添加 WHERE 子句以过滤单个客户或删除所有条目。左连接也会带来空列。

答案 2 :(得分:0)

似乎正是您所追求的;只需几个 JOIN 和一个转轴:

SELECT C.CustID,
       V.Notes,
       V.Col1
FROM dbo.Customer C
     JOIN dbo.Payment P ON C.CustID = P.CustID --Might need to be a LEFT JOIN
     JOIN dbo.Refund R ON C.CustID = R.CustID --Might need to be a LEFT JOIN
     CROSS APPLY(VALUES(C.Notes,1),
                       (P.PmtNotes,2),
                       (R.RefNotes,3))V(Notes,Col1)
WHERE C.CustID = 3
  AND V.Notes IS NOT NULL;
相关问题