四列基于四个键

时间:2017-05-18 12:13:04

标签: sql sql-server

我首先根据包含5个数字和一年(有时+ B)的信息制作了一张表:

SELECT  number5,    
YEAR(MyDate) AS [year], 
            concat(a.[number5],'-',YEAR(MyDate)) AS [A1],  
            concat(a.[number5],'-',YEAR(MyDate)-1) AS [A1-1],
            concat(a.[number5], '-',YEAR([MyDate]),'B') AS [B1],
            concat(a.[number5],'-',YEAR(MyDate)-1,'B') AS [B1-1]

 INTO #temp
 FROM aTable

所以你会得到:

number5 year   A1          A1-1         B1           B1-1
12345   2001   12345-2001  12345-2000   12345-2001B  12345-2000B   
23456   2002   23456-2002  23456-2001   23456-2002B  23456-2001B
34569   2003   34569-2003  34569-2002   34569-2003B  34569-2002B
45678   2004   45678-2004  45678-2003   45678-2004B  45678-2003B

然后我将此表与其他信息一起加入:

FileName        Value    Brand
12345-2001      10000    Apple
23456-2002      30409    Microsoft
34569-2003      09283    Microsoft
12345-2001B     20398    Apple
45678-2003B     20384    Apple

SELECT * FROM OtherTable AS a LEFT JOIN #temp AS b ON
b.A1 = a.Filename

但是,这会为一行提供值,为另一行提供NULL值。我如何编程它能够理解如果我将FileName与A1,A1-1,B1和B1-1中的一列连接起来,它还将信息放在新列中。所以:

Numb5   year   A1            A1-1           B1          B1-1        FileN. Value     Brand    FileN. Value Brand     FileN.        Value  Brand.
12345   2001   12345-2001  12345-2000   12345-2001B  12345-2000B 12345-2001 10000    Apple                        12345-2001B     20398    Apple

我已经尝试过自我加入(但可能是错误的):

WITH RLT AS (
SELECT *, Row_number() over (PARTITION BY [FileName] ORDER BY [year] Desc) RN FROM OtherTable)

所以我想要的是它在第1行A1中查找值:12345-2001并返回以下值: FileName Value Brand

然后查找同一行中的第二个值:12345-2000并返回以下值: FileName价值品牌。

但是,我希望它们彼此相邻,所以:

A1   A1-1 B1  B1-1  FileName (A1)  Value (A1)  Brand (A1)  FileName (A1-1) Value (A1-1) Brand (A1-1)  FileName (B1) Value (B1) Brand (B1) FileName (B1-1) Value (B1-1) Brand (B1-1). 

1 个答案:

答案 0 :(得分:3)

听起来就像您说的那样,当您查询This is line string1 This is line two with string1 and string3 string1 This is line two with string1 string1 and string3 This is line three with string3 This is line string3 with string1 and string1 时,某些public class ObjectWrapper { private String col1; private String col2; // getter and setters; public String toString(){ return "col1: " + col1 + "col2: " + col2; } } ArrayList<ObjectWrapper> dataList = new ArrayList<ObjectWrapper>(); for (int i = 0; i < jArray.length(); i++) { JSONObject json_data = jArray.getJSONObject(i); ObjectWrapper obj = new ObjectWrapper(); obj.setCol1(json_data.getString("col1"))); obj.setCol2(json_data.getString("col2"))); dataList.add(obj); } for (ObjectWrapper line : dataList) { System.out.println("this is the element in the arraylist>>>>> " +line); } 条记录找不到匹配的OtherTable LEFT JOIN #temp记录,因此OtherTable个单元格会显示在旁边#temp记录,我是对的吗?

基于这种理解,您提供的最后一个数据样本以及问题的其余部分,我认为这正是您所寻找的:

NULL