简体   繁体   中英

how to select single row from one table and multiple rows from another table toghether?

i have a following table users which has following definition

 id integer 
 Name varchar
 Email varchar 
 Location varchar
 Phone varchar
 Picture varchar
 Status varchar

and i have another table userskills which has following definition

id integer
 Userid integer
 Skill   integer

no i want to combine the two tables and select single row from first table while multiple rows from another table as user can have multiple skills but i'm getting multiple rows of user data but i want a single row? can anybody tell me how to get user and its corresponding skills in an single row?

You can do it with a PIVOT. You would select the skills from the skills table and then pivot them into a single row. Then JOIN with the user.

Here is an example with a fixed number of skills.

WITH TEMP AS
(
 SELECT 'John' AS U, 'Driver' AS S
 UNION ALL
 SELECT 'John' AS U, 'Plumber' AS S
 UNION ALL
 SELECT 'Jim' AS U, 'Driver' AS S
 UNION ALL
 SELECT 'Tom' AS U, 'Driver' AS S
)

SELECT * FROM 
( SELECT *, U AS DRIVER FROM TEMP ) AS P
PIVOT
(
    COUNT([U])
    FOR S IN ([Driver],[Plumber])
) AS PIV

If you have a variable number of skills you are going to have to query that first, then transform that into a string and run EXEC on the string.

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