简体   繁体   中英

SQL Server - Group by with multiple joins and strings

I have searched many similiar topics but am still struggling to get this working. I am trying to group on one column in particular after doing a few table joins. Any help wouldbe greatly appreciated

OUTPUT TODAY

Account System  System  Plan Code   Account Plan Code   Request
12345   Sys1    Sys1    P1         12345    P1          00001
12345   Sys1    Sys1    P2         NULL     NULL        NULL
12345   Sys2    Sys2    P3         12345    P3          00002
34567   Sys1    Sys1    P1         NULL     NULL        NULL
34567   Sys1    Sys1    P2         34567    P2          00003
45678   Sys3    Sys3    P4         NULL     NULL        NULL

DESIRED OUTPUT

Account System  System  Plan Code   Account Plan Code   Request
12345   Sys1    Sys1    P1          12345   P1, P2      00001
12345   Sys2    Sys2    P3          12345   P3          00002
34567   Sys1    Sys1    P2          34567   P1,P2       00003
45678   Sys3    Sys3    P4          NULL    NULL        NULL

I am joining a few tables and I want to combine the Plan Codes into one row per each unique Account to System Mapping.

  • Tab1 = Account and System
  • Tab2 = System and Plan Code (Mapping that shows what plan codes are related to each system)
  • Tab3 = Account,Plan Code, Request #

I get lost with the group by I tried a one column GROUP BY and get the error that is not a GROUP By Expression. So then I included all the columns and that does not change the output at all.

SELECT      A.ACCOUNT, A.SYSTEM, B.SYSTEM, B.PCODE, C.ACCOUNT, C.PCODE, C.REQUEST
FROM        MYDB.TAB1 A
LEFT JOIN   MYDB.TAB2 B 
ON      A.SYSTEM = B.SYSTEM
LEFT JOIN   MYDB.TAB3 C
ON      A.ACCOUNT = C.ACCOUNT AND B.PCODE = C.PCODE
WHERE       A.ACCOUNT IS NOT NULL
ORDER BY    A.ACCOUNT

If you do not need to concatenate plans, then please see if the following GROUP BY implementation could suit your needs. I removed several columns for this script. To comply with aggregate query limitations I used MAX around C.PCODE (which could be MIN as well) and MAX for C.REQUEST which seems to be a good choice to get rid of NULL s there.

SELECT      A.ACCOUNT, A.SYSTEM, MAX(C.PCODE), MAX(C.REQUEST)
FROM        MYDB.TAB1 A
LEFT JOIN   MYDB.TAB2 B 
ON      A.SYSTEM = B.SYSTEM
LEFT JOIN   MYDB.TAB3 C
ON      A.ACCOUNT = C.ACCOUNT AND B.PCODE = C.PCODE
WHERE       A.ACCOUNT IS NOT NULL
GROUP BY A.ACCOUNT, A.SYSTEM
ORDER BY    A.ACCOUNT

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