I have 2 tables:
camp_1 col_1 camp_2 col_2
1 2 3 2 4 6 3 6 9 4 8 12
I want to create a statement to use results from t1
in the SELECT list for t2
and show t2
results.
Example:
Step 1: get results from table 1
select col_name from t1 where campaign_name = 'camp_1'
Result: col_1
Step 2: Use the result ( col_1
) for t2 and show the corresponding results
select col_1 from t2
The end results should be
1 2 3 4
Consider to change your schema to something like this:
camp_1 col_1 camp_2 col_2
group1 col_1 1 group1 col_2 2 group1 col_3 3 group2 col_1 2 group2 col_2 4 group2 col_3 6 group3 col_1 3 group3 col_2 6 group3 col_3 9 group4 col_1 4 group4 col_2 8 group4 col_3 12
You can then select:
SELECT num
FROM t1
JOIN t2 ON t1. col_name = t2. col_name
WHERE t1.campaign_name = 'camp_1'
Benefits:
If you cannot change your schema, there is still a possibility to select the values without dynamic SQL. You can use the elaboratet feature UNPIVOT
- which converts data from several columns into data in additional rows.
WITH unpivot_t2 AS (
SELECT *
FROM t2
UNPIVOT
(value FOR col_name IN (col_1, col_2, col_3))
AS unpvt
)
SELECT value
FROM unpivot_t2
JOIN t1 ON t1.col_name = unpivot_t2.col_name
WHERE campaign_name = 'camp_1'
With this DDL:
CREATE TABLE t1 (
campaign_name varchar(255),
col_name varchar(255)
)
INSERT INTO t1 VALUES
('camp_1', 'col_1'),
('camp_2', 'col_2')
CREATE TABLE t2 (
col_1 varchar(255),
col_2 varchar(255),
col_3 varchar(255)
)
INSERT INTO t2 VALUES
(1,2,3),
(2,4,6),
(3,6,9),
(4,8,12)
If you cannot change your schema as slartidan said. Then, first, you have to get your required column name(s) from the table, t1 .
Way One (Using SQL Concatenation)
DECLARE @Columns VARCHAR(MAX) = ''
SELECT @Columns = @Columns + col_name + ','
FROM t1
WHERE campaign_name = 'camp_1'
GROUP BY col_name
SET @Columns = LEFT(@Columns,LEN(@Columns)-1)
Way Two (Using FOR XML PATH):
DECLARE @Columns VARCHAR(MAX) = ''
SELECT @Columns = STUFF((SELECT ',' + col_name
FROM t1
WHERE campaign_name = 'camp_1'
GROUP BY col_name
FOR XML PATH('')) ,1,1,'')
Then you have to execute a raw SQL.
EXEC ('SELECT ' + @Columns + ' FROM t2')
Hope, Then you can get dynamic column values from your desired table, t2 .
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.