簡體   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