简体   繁体   English

如何从一个表中选择单行和从另一个表中选择多行?

[英]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.你可以用 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.如果您有可变数量的技能,您将必须首先查询它,然后将其转换为字符串并在该字符串上运行 EXEC。

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

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