简体   繁体   中英

Using a SQL join table as extra columns

Im trying to write a query that pulls out data from a couple of other tables as columns in the query.

Here is the data:

User table

ID    ACCOUNT_ID    FIRST_NAME        LAST_NAME
1         1             Joe            SMITH
2         1             Bill           WALTERS
3         1             Bill           JOHNSON

User Fields Table

ID      ACCOUNT_ID     NAME
 1         1            CITY
 2         1            STATE
 3         2            EMPLOYEE_NUMBER
 4         3            MIDDLE_NAME

User Fields Data Table

ID    USER_FIELD_ID      USER_ID     DATA
 1         1               1         LINCOLN
 2         2               1         NEBRASKA

I would like a query something like:

SELECT FIRST_NAME, LAST_NAME FROM users WHERE ACCOUNT_ID=1

But I would like it to include CITY and STATE as columns, but these will be different based on the ACCOUNT_ID and the data in the User Fields table.

I'm thinking this might be accomplished with PIVOT, but I am having a hard time getting it to work. Thanks!

using this code will act similar to a PIVOT. You would need to add a MAX(CASE) for each User Field type you want. Since it is using an Aggregate, you will only get one value from User Fields Data for each User Field

SELECT  u.FIRST_NAME, 
        u.LAST_NAME, 
        uf.CITY, 
        uf.STATE
FROM    users u
        LEFT JOIN (SELECT   uf.ACCOUNT_ID,
                            ufd.USER_ID,
                            MAX(CASE WHEN uf.NAME = 'CITY' THEN [DATA] END) AS CITY,
                            MAX(CASE WHEN uf.NAME = 'STATE' THEN [DATA] END) AS STATE
                   FROM     UserFields uf
                            JOIN UserFieldData ufd ON uf.ID = ufd.USER_FIELD_ID
                   GROUP BY uf.ACCOUNT_ID,
                            ufd.USER_ID
                  ) uf ON uf.USER_ID = u.ID
                          AND uf.ACCOUNT_ID = u.ACCOUNT_ID
WHERE   u.ACCOUNT_ID = 1

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