简体   繁体   中英

sql where same values different columns

I'd like to group the values that are in the BelNr2 column to those that are the same in the BelNr1 column. Ie if the following was the table: Name: 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

I would like it to be grouped as follows with 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

Thanks in advance for help.

A simple where clause does the trick.. based on what you wrote as expected result, you don't need group by.

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

If you want to cross reference between rows, you can do a JOIN with the same table:

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

The following sql returns the result I want.

Thank you.

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 "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM