如何基于合并的列合并具有以下联接的列?

时间:2018-08-23 13:37:32

标签: sql sql-server

How to merge many(and different) cells from one row to many rows with fewer cells?
我得到了一半的答案,因为在此步骤之后,有一张表要连接到与该数据有关的合并数据之上。 因此,例如,现在有2个表,MainTableTypes(我从中得到Id s个。
从(MainTable)开始:

Name | Date       | Type_0 | Mess_0 | Type_1 | Mess_1 | Type_2 | Mess_2 
"AD" | 2018-03-02 | "error"| "mess" | "warn" | "mess" | "info" | "mess"

收件人(MainTable):

Name | Date       | Type   | Mess   | TypeId
"AD" | 2018-03-02 | "error"| "mess" | 1
"AD" | 2018-03-02 | "warn" | "mess" | 2
"AD" | 2018-03-02 | "info" | "mess" | 3

使用从表TypeId获得的Types
类型Type_X的名称在Id中具有DescriptionTypes。 br /> 最终查询如下:

SELECT Name,Date,Type,Mess,T.Id
FROM   MainTable
   CROSS APPLY
   (
       SELECT Type = Type_0, Mess = Mess_0, ColName = 'Type_0'
       UNION ALL
       SELECT Type = Type_1, Mess = Mess_1, ColName = 'Type_1'
       UNION ALL
       SELECT Type = Type_2, Mess = Mess_2, ColName = 'Type_2'
   ) TM
INNER JOIN Types T
ON TM.ColName LIKE T.Description + '%'

没有最后一个内部联接,我得到了我想要的东西,但是在最后一个内部联接之后,我得到了最后一个联合的三份副本:

SELECT Type = Type_2, Mess = Mess_2, ColName = 'Type_2'

哪个都弄乱了,例如:

Name | Date       | Type   | Mess   | TypeId
"AD" | 2018-03-02 | "error"| "mess" | 1
"AD" | 2018-03-02 | "warn" | "mess" | 2
"AD" | 2018-03-02 | "info" | "mess" | 3
"AD" | 2018-03-02 | "info" | "mess" | 3
"AD" | 2018-03-02 | "info" | "mess" | 3

有人知道吗?



Ps:Types表应要求提供:

Id | Description
1  | 'HVaR_3Y_6M'
2  | 'HVaR_3Y_1Y'
3  | 'HVaR_3Y'

2 个答案:

答案 0 :(得分:1)

问题显然是HVaR_3Y是所有三个描述的前缀,因此它与其他两个描述匹配三倍。

答案 1 :(得分:0)

也许最后一行在“类型”表中有多个匹配项。如果您希望交叉应用的结果(主表和TM)保持不变,而无论Types表中的内容是什么,请使用Left Join:

SELECT Name,Date,Type,Mess,T.Id
FROM   MainTable
   CROSS APPLY
   (
       SELECT Type = Type_0, Mess = Mess_0, ColName = 'Type_0'
       UNION ALL
       SELECT Type = Type_1, Mess = Mess_1, ColName = 'Type_1'
       UNION ALL
       SELECT Type = Type_2, Mess = Mess_2, ColName = 'Type_2'
   ) TM
LEFT JOIN Types T
ON TM.ColName LIKE T.Description + '%'