简体   繁体   中英

Selecting Multiple Values from Single Column

I have the following table:

att_id | user_id | att_name  | att_value
1      | 202     | first_name| Cris    
2      | 202     | last_name | Williams
3      | 202     | email     | cwill122@yahoo.com

I want to return a table like:

202  | Chris | Wiliams | cwill122@yaoo

You can do conditional aggregation. This is the cannonical way to pivot a dataset:

select 
    user_id,
    max(case when att_name = 'first_name' then att_value end) first_name,
    max(case when att_name = 'last_name'  then att_value end) last_name,
    max(case when att_name = 'email'      then att_value end) email
from mytable
group by user_id

我的建议是将字段att_name att_value放在另一个表中并进行连接

You'll need to self-join the table, giving it aliases.

SELECT t1.att_value, t2.att_value, t3.att_value FROM [tablename] t1 JOIN [tablename] t2 ON t1.att_id = t2.att_id JOIN [tablename] t3 ON t3.att_id = t1.att_id WHERE user_id = 202

Store the user_id in a variable(say uid) and then take the first_name, last_name, email of uid in other variables. Then u can insert them into a new table. Or u can use join to do the work and create a view to use in in future.

You can use a PIVOT(MSSQL/TSQL).

WITH PivotData AS
(
    SELECT user_id, att_name, att_value FROM dbo.AttTable
)
SELECT user_id, first_name, last_name, email
FROM PivotData
    PIVOT(MAX(att_value) FOR att_name IN(first_name, last_name, email)) AS P;

Test data

CREATE TABLE dbo.AttTable
(
    att_id INT NOT NULL,
    user_id INT NOT NULL,
    att_name VARCHAR(50) NOT NULL,
    att_value VARCHAR(50) NOT NULL,
    PRIMARY KEY (att_id, user_id)
);

INSERT INTO dbo.AttTable
    (att_id, user_id, att_name, att_value)
VALUES
    (1, 202, 'first_name', 'Cris'),
    (2, 202, 'last_name', 'Williams'),
    (3, 202, 'email', 'cwill122@yahoo.com')
select 
    I.user_id,A.fname, B.lname, C.email
    from 
    (select distinct user_id from AttTable) I
    left join 
    (select user_id, att_value as fname from AttTable where att_name = 'first_name') A
    on I.user_id =  A.user_ID
    left join
    (select user_id, att_value as lname from AttTable where att_name = 'last_name') B
    on I.user_id = B.user_id
    left join 
    (select user_id, att_value as email from AttTable where att_name = 'email') C
    on I.user_id = C.user_id 

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