SQL将同一表中的多行合并为同一行

问题描述

我有两个表,并且表1(客户)仅具有有限的行数,因此我希望能够在此表(客户)中输入客户信息,然后将其保存在两行中以便能够读取这两行并将其组合为一行,并使用sql将其显示为一行。

我能够正常读取表,将Customer数据库与CustomerDetails数据库链接在一起,因为CustomerDetails包含在客户中显示列所需的唯一值

SELECT c.Cust_4,c.Cust_5,C.Cust_6  //Selecting the rows to display from Customer
FROM Customer C //From the Customer Database,as C
LEFT JOIN CustomerDetails CD ON C.Unique_val = CD.Unique_val. Joining the Customer DB with CustomerDetails DB,where the 'Unique_val' is the same.

INNER JOIN (SELECT Cust_40,MAX(CREATE_DT) AS MaxTime FROM Customers GROUP BY Cust_40)
grouped ON grouped.Cust_40 = C.Cust_40 //Taking the latest created entry in the Customer Database,Grouped by Cust_40,so it reads the most RECENT version

WHERE grouped.MaxTime = C.CREATE_DT //
AND CD.F_ID = 12332131 //The UNIQUE value inside of the CustomerDetails Database

结果:

c.Cust_4     c.Cust_5     C.Cust_6
 Info1         Info2        Info3

在这可以正常工作,它将始终读取最新行GROUPING Cust_40,因此,如果有10个条目WHERE Cust_40 ='DavesRow',那么它将为'DavesRow'显示1行,并带有最新值。

现在,可以说客户数据库的行数有限,所以我希望有20行,但只有10行。 现在,我的目标是自己与客户数据库“自我结合”,读取两行或更多行,并将其合并为同一行,其中某些值相同。

这是两行的示例,

Cust_4     Cust_5     Cust_6    Cust_40
 Info1      Info2      Info3    DavesRow


Cust_4     Cust_5     Cust_6    Cust_40
Info4       Info5      Info6    DavesRow

我尝试用sql将这些行合并为一行:

SELECT c.Cust_4,c.Cust_6 d.Cust_4,d.Cust_5,d.Cust_6 //reading the same 3 rows,but from two different entries
    FROM Customer C 
    INNER JOIN Customers D ON D.Cust_39 = C.Cust_39 //SELF JOINING Customers ON Customers where CUST_39 is the same value

    LEFT JOIN CustomerDetails CD ON C.Unique_val = CD.Unique_val  // Joining the Customer DB with CustomerDetails DB,where the 'Unique_val' is the same.
    
    INNER JOIN (SELECT Cust_40,MAX(CREATE_DT) AS MaxTime FROM Customers GROUP BY Cust_40)
    grouped ON grouped.Cust_40 = C.Cust_40 //Taking the latest created entry in the Customer Database,so it reads the most RECENT version
    
    WHERE grouped.MaxTime = C.CREATE_DT 
    AND grouped.MaxTime = D.CREATE_DT // THE CREATE_DT WILL BE THE SAME FOR EACH ROW 

    AND CD.F_ID = 12332131 //the CustomerDetails F_ID value will be different,it will be '12332131' for the 'C' instance of Customers,and '13424251' for the 'D' instance of Customers
    AND CD.F_ID = 13424251 

这无法正常运行...在所有6行中显示c.Cust_4,c.Cust_5和c.Cust_6的值:c.Cust_4,c.Cust_5,c.Cust_6,d.Cust_4, d.Cust_5,d.Cust_6

结果

c.Cust_4     c.Cust_5     c.Cust_6    d.Cust_4    d.Cust_5    d.Cust_6   
  Info1       Info2       Info3        Info1       Info2       Info3   

所需结果

c.Cust_4     c.Cust_5     c.Cust_6    d.Cust_4    d.Cust_5    d.Cust_6   
  Info1       Info2       Info3        Info4       Info5       Info6

我希望我已经解释好了...

任何帮助将不胜感激。谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)