sql中相同的值不同的列

时间:2019-07-02 18:18:28

标签: sql excel vba

我想将BelNr2列中的值与BelNr1列中的值分组。 即如果下面是表:名称:MyTable

CusID |  BelNr1 | BelNr2 | BelTy | BelYr |  Amnt
1001    2000101   2000101    AB     2018     500
1001    2000102   2000102    AB     2018     750
1001    2000118   2000103    AB     2018     800
1002    2000104   2000104    AB     2018    1200
1002    2000105   2000105    AB     2018    1300
1003    2000106   2000106    AB     2018     900
1003    2000115   2000109    AB     2018     950
1004    2000107   2000107    AB     2018    1000
1005    2000104   2000108    AB     2018     910

我希望使用SQL将其分组如下

CusID  | BelNr2  |  Amnt
1001    2000101      500     'Row 1 = Row 1 BelNr2 = BelNr1
1001    2000102      750     'Row 2 = Row 2 BelNr2 = BelNr1
1002    2000104     1200     'Row 4 = Row 4 BelNr2 = BelNr1
1002    2000104      910     'Row 4 = Row 9 BelNr2 = BelNr1
1002    2000105     1300     'Row 5 = Row 5 BelNr2 = BelNr1
1003    2000106      900     'Row 6 = Row 6 BelNr2 = BelNr1
1004    2000107     1000     'Row 8 = Row 8 BelNr2 = BelNr1

预先感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

一个简单的where子句就可以解决问题。.根据您期望的结果编写内容,不需要分组依据。

select CusID, BelNr2, Amnt
from MyTable
where BelNr2=BelNr1

如果要在行之间交叉引用,可以对同一张表进行JOIN操作:

SELECT T1.CusID, T2.BelNr2, T2.Amnt
FROM MyTable T1
         JOIN MyTable T2 ON T1.BelNr2 = T2.BelNr1

答案 1 :(得分:0)

以下sql返回我想要的结果。

谢谢。

sql = "SELECT " & _
   "t1.CusID, t1.BelNr2, t2.Amnt " & _
"FROM " & _
   "( " & _
       "SELECT " & _
           "CusID, BelNr2, Amnt " & _
       "FROM " & _
           "[MyTable$] " & _
   ") AS t1 " & _
   "inner Join " & _
   "( " & _
       "SELECT " & _
           "BelNr1, Amnt " & _
       "FROM " & _
           "[MyTable$]" & _
   ") AS t2 " & _
       "ON t1.BelNr2 = t2.BelNr1 "