繁体   English   中英

从单列中选择多个值

[英]Selecting Multiple Values from Single Column

我有下表:

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

我想返回一个表,如:

202  | Chris | Wiliams | cwill122@yaoo

您可以进行条件聚合。 这是旋转数据集的规范方法:

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放在另一个表中并进行连接

您需要自行加入该表,并为其指定别名。

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

将 user_id 存储在一个变量中(比如 uid),然后在其他变量中获取 uid 的 first_name、last_name、email。 然后你可以将它们插入到一个新表中。 或者您可以使用 join 来完成工作并创建一个视图以供将来使用。

您可以使用 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;

测试数据

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 

暂无
暂无

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

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