A
A
ALexLancer2020-08-09 12:28:22
SQL
ALexLancer, 2020-08-09 12:28:22

How to select 3 columns in SQL?

How to
5f2fc192796f6694804096.jpeg
get such a selection from such a table in SQL It is
5f2fc1aa15b92262854391.jpeg

necessary to take not all user_id from the table, but from a given array of identifiers

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2020-08-09
@Alexandre888

select duplicates from table:

SELECT min(user_id), gender, age
FROM table
GROUP BY gender, age

K
Konstantin Tsvetkov, 2020-08-09
@tsklab

It's called PIVOT. Did it recently .
For you:

DECLARE @UserInfo TABLE ( user_id INT, meta_key VARCHAR(100), meta_value VARCHAR(100) )
INSERT @UserInfo VALUES ( 1, 'gender', 'male' ),
( 1, 'age', '21' ),
( 2, 'gender', 'female' ),
( 2, 'age', '23' ),
( 3, 'gender', 'genderqueer' ),
( 4, 'age', '25' ),
( 4, 'location', 'toster' ),
( 5, 'gender', 'male' ),
( 5, 'age', '27' ),
( 6, 'gender', 'female' ),
( 6, 'age', '29' )

SELECT user_id, gender, age, location
  FROM ( SELECT * FROM @UserInfo ) AS UI
  PIVOT ( MAX( meta_value ) FOR meta_key IN (gender, age, location )) AS PT
  WHERE user_id BETWEEN 2 AND 5
  ORDER BY user_id

Result:
user_id	gender	age	location
2	female	23	NULL
3	genderqueer	NULL	NULL
4	NULL	25	toster
5	male	27	NULL

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question