简体   繁体   English

使用SQL连接表作为额外的列

[英]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. 但是我希望将CITY和STATE作为列包括在内,但是根据ACCOUNT_ID和“用户字段”表中的数据,它们将有所不同。

I'm thinking this might be accomplished with PIVOT, but I am having a hard time getting it to work. 我以为使用PIVOT可以实现此目的,但是我很难将其发挥作用。 Thanks! 谢谢!

using this code will act similar to a PIVOT. 使用此代码的行为将类似于PIVOT。 You would need to add a MAX(CASE) for each User Field type you want. 您需要为所需的每个User Field类型添加一个MAX(CASE) Since it is using an Aggregate, you will only get one value from User Fields Data for each User Field 由于它使用的是汇总,因此对于每个User Field ,您只能从User Fields Data获得一个值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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