Is it possible to alias a column based on the result of a select+where?Select multiple rows from one row...
What was the first science fiction or fantasy multiple choice book?
The alcoholic village festival
Can US Supreme Court justices / judges be "rotated" out against their will?
Having to constantly redo everything because I don't know how to do it
How would one prevent political gerrymandering?
Dynamic Sql Query - how to add an int to the code?
Why are symbols not written in words?
Checkmate in 1 on a Tangled Board
How to track mail undetectably?
I agreed to cancel a long-planned vacation (with travel costs) due to project deadlines, but now the timeline has all changed again
Why isn't UDP with reliability (implemented at Application layer) a substitute of TCP?
Why is exile often an intermediate step?
What does 'in attendance' mean on an England death certificate?
Customs and immigration on a USA-UK-Sweden flight itinerary
Hard for me to understand one tip written in "The as-if rule" of cppreference
Reusable spacecraft: why still have fairings detach, instead of open/close?
Why are examinees often not allowed to leave during the start and end of an exam?
Why will we fail creating a self sustaining off world colony?
How does the 'five minute adventuring day' affect class balance?
What prevents a US state from colonizing a smaller state?
Is this house-rule removing the increased effect of cantrips at higher character levels balanced?
How to count the number of bytes in a file, grouping the same bytes?
Two palindromes are not enough
Is there a list of all of the cases in the Talmud where תיקו ("Teiku") is said?
Is it possible to alias a column based on the result of a select+where?
Select multiple rows from one row based on column valuesSelect the newest data (inner join + group by maybe)Using expressions in the SELECT list to thin down a CASE statementFinding the Table and Column Based on a Known ValueReplacement for Nested SELECT statements for every row in SELECT clauseCan I create a computed column that requires input to select?Is there a rule of thumb for including the value of a foreign key in a table to avoid large joins?SQL Server Error 8632 due to over 100,000 entries in WHERE clauseSimilar query, run times much differentComparing two pairs of columns between two tables and returning the column from a third table
I have a table like this:
TB1:
COD | A001 | A002 | A003
1 cars baby nasa
and then a second table:
TB2:
COD | NO_COL_TB1 | DESCRIPTION |
1 | A001 | Something
2 | A002 | lasagna
What I'm trying to do is something like this ( obviously this doesnt work )
select A001 as (select description from TB2 WHERE no_col_tb1= A001 )
,A002 AS (select description from TB2 WHERE no_col_tb1= A002 )
from TB1
i tried with inner joins and some dynamic sql but I just can't think in a logic for this. There's some questions about this but none of them could help me. I think this is impossible to do with a single statement and only possible with a Dynamic SQL.
EDIT:
The correct result would be:
SELECT COD,
TB1.A001 AS 'Something',
TB1.A002 AS 'Lasagna'
FROM TB1
and the result would be:
COD |SOMETHING | LASAGNA |
1 cars baby
sql-server sql-server-2008
add a comment |
I have a table like this:
TB1:
COD | A001 | A002 | A003
1 cars baby nasa
and then a second table:
TB2:
COD | NO_COL_TB1 | DESCRIPTION |
1 | A001 | Something
2 | A002 | lasagna
What I'm trying to do is something like this ( obviously this doesnt work )
select A001 as (select description from TB2 WHERE no_col_tb1= A001 )
,A002 AS (select description from TB2 WHERE no_col_tb1= A002 )
from TB1
i tried with inner joins and some dynamic sql but I just can't think in a logic for this. There's some questions about this but none of them could help me. I think this is impossible to do with a single statement and only possible with a Dynamic SQL.
EDIT:
The correct result would be:
SELECT COD,
TB1.A001 AS 'Something',
TB1.A002 AS 'Lasagna'
FROM TB1
and the result would be:
COD |SOMETHING | LASAGNA |
1 cars baby
sql-server sql-server-2008
Erik, The result would be the same as a "select * from tb1, but column names would be theDescription
from TB2. I will edit...I don't think its a case because I don't want to change the value of the result, I would like to change the "colum name" from TB1 based on a result from TB2. I would like to change the alias dynamically. TB1 has a column named A001, and on TB2 I have a descriptionA001 = Something
. Using this, I would like to use this value as a column name. I' trying using STUFF and I'm testing right now...
– Racer SQL
9 hours ago
This feels like an EAV. Bad. Really bad. Dynamic SQL ( :( ) would be required.
– Michael Kutz
9 hours ago
2
Well, I don't know how "really bad" EAV is, but agree with Michael, dynamic SQL will be required.
– Aaron Bertrand♦
9 hours ago
add a comment |
I have a table like this:
TB1:
COD | A001 | A002 | A003
1 cars baby nasa
and then a second table:
TB2:
COD | NO_COL_TB1 | DESCRIPTION |
1 | A001 | Something
2 | A002 | lasagna
What I'm trying to do is something like this ( obviously this doesnt work )
select A001 as (select description from TB2 WHERE no_col_tb1= A001 )
,A002 AS (select description from TB2 WHERE no_col_tb1= A002 )
from TB1
i tried with inner joins and some dynamic sql but I just can't think in a logic for this. There's some questions about this but none of them could help me. I think this is impossible to do with a single statement and only possible with a Dynamic SQL.
EDIT:
The correct result would be:
SELECT COD,
TB1.A001 AS 'Something',
TB1.A002 AS 'Lasagna'
FROM TB1
and the result would be:
COD |SOMETHING | LASAGNA |
1 cars baby
sql-server sql-server-2008
I have a table like this:
TB1:
COD | A001 | A002 | A003
1 cars baby nasa
and then a second table:
TB2:
COD | NO_COL_TB1 | DESCRIPTION |
1 | A001 | Something
2 | A002 | lasagna
What I'm trying to do is something like this ( obviously this doesnt work )
select A001 as (select description from TB2 WHERE no_col_tb1= A001 )
,A002 AS (select description from TB2 WHERE no_col_tb1= A002 )
from TB1
i tried with inner joins and some dynamic sql but I just can't think in a logic for this. There's some questions about this but none of them could help me. I think this is impossible to do with a single statement and only possible with a Dynamic SQL.
EDIT:
The correct result would be:
SELECT COD,
TB1.A001 AS 'Something',
TB1.A002 AS 'Lasagna'
FROM TB1
and the result would be:
COD |SOMETHING | LASAGNA |
1 cars baby
sql-server sql-server-2008
sql-server sql-server-2008
edited 9 hours ago
Racer SQL
asked 9 hours ago
Racer SQLRacer SQL
3,2424 gold badges28 silver badges68 bronze badges
3,2424 gold badges28 silver badges68 bronze badges
Erik, The result would be the same as a "select * from tb1, but column names would be theDescription
from TB2. I will edit...I don't think its a case because I don't want to change the value of the result, I would like to change the "colum name" from TB1 based on a result from TB2. I would like to change the alias dynamically. TB1 has a column named A001, and on TB2 I have a descriptionA001 = Something
. Using this, I would like to use this value as a column name. I' trying using STUFF and I'm testing right now...
– Racer SQL
9 hours ago
This feels like an EAV. Bad. Really bad. Dynamic SQL ( :( ) would be required.
– Michael Kutz
9 hours ago
2
Well, I don't know how "really bad" EAV is, but agree with Michael, dynamic SQL will be required.
– Aaron Bertrand♦
9 hours ago
add a comment |
Erik, The result would be the same as a "select * from tb1, but column names would be theDescription
from TB2. I will edit...I don't think its a case because I don't want to change the value of the result, I would like to change the "colum name" from TB1 based on a result from TB2. I would like to change the alias dynamically. TB1 has a column named A001, and on TB2 I have a descriptionA001 = Something
. Using this, I would like to use this value as a column name. I' trying using STUFF and I'm testing right now...
– Racer SQL
9 hours ago
This feels like an EAV. Bad. Really bad. Dynamic SQL ( :( ) would be required.
– Michael Kutz
9 hours ago
2
Well, I don't know how "really bad" EAV is, but agree with Michael, dynamic SQL will be required.
– Aaron Bertrand♦
9 hours ago
Erik, The result would be the same as a "select * from tb1, but column names would be the
Description
from TB2. I will edit...I don't think its a case because I don't want to change the value of the result, I would like to change the "colum name" from TB1 based on a result from TB2. I would like to change the alias dynamically. TB1 has a column named A001, and on TB2 I have a description A001 = Something
. Using this, I would like to use this value as a column name. I' trying using STUFF and I'm testing right now...– Racer SQL
9 hours ago
Erik, The result would be the same as a "select * from tb1, but column names would be the
Description
from TB2. I will edit...I don't think its a case because I don't want to change the value of the result, I would like to change the "colum name" from TB1 based on a result from TB2. I would like to change the alias dynamically. TB1 has a column named A001, and on TB2 I have a description A001 = Something
. Using this, I would like to use this value as a column name. I' trying using STUFF and I'm testing right now...– Racer SQL
9 hours ago
This feels like an EAV. Bad. Really bad. Dynamic SQL ( :( ) would be required.
– Michael Kutz
9 hours ago
This feels like an EAV. Bad. Really bad. Dynamic SQL ( :( ) would be required.
– Michael Kutz
9 hours ago
2
2
Well, I don't know how "really bad" EAV is, but agree with Michael, dynamic SQL will be required.
– Aaron Bertrand♦
9 hours ago
Well, I don't know how "really bad" EAV is, but agree with Michael, dynamic SQL will be required.
– Aaron Bertrand♦
9 hours ago
add a comment |
2 Answers
2
active
oldest
votes
Sorry to say but your table structure is difficult to work with considering what you want to do. There are various ways you can probably get the result, one way would be to use UNPIVOT
and PIVOT
, but it's ugly.
You could start by UNPIVOT
ing the date in TB1
from your columns to rows:
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
This is going to return the data in the format of:
| COD | val | col |
|-----|------|------|
| 1 | cars | A001 |
| 1 | baby | A002 |
| 1 | nasa | A003 |
Then you could take that result and join it to TB2
:
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1;
Which gives the result:
| COD | val | DESCRIPTION |
|-----|------|-------------|
| 1 | cars | Something |
| 1 | baby | lasagna |
Now you have your new column names in the Description
and the val
in rows, but you want them in columns, so now you can apply the PIVOT
function to it:
select *
from
(
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1
) x
pivot
(
max(val)
for description in (Something, Lasagna)
) p;
This generates the final result you want:
| COD | Something | Lasagna |
|-----|-----------|---------|
| 1 | cars | baby |
Now all that is great if you know all the columns that you need to UNPIVOT
and then PIVOT
, but if you don't then you'll need to use dynamic SQL to solve it. Which will look something like this:
DECLARE
@colsUnpivot AS NVARCHAR(MAX),
@colsPivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsUnpivot
= stuff((select ','+quotename(C.column_name)
from information_schema.columns as C
where C.table_name = 'tb1' and
C.column_name like 'A%'
for xml path('')), 1, 1, '')
select @colsPivot
= stuff((select ','+quotename([DESCRIPTION])
from Tb2
for xml path('')), 1, 1, '')
set @query = 'select *
from
(
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in ('+ @colsUnpivot +')
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1
) x
pivot
(
max(val)
for description in ('+@colsPivot+')
) p;';
exec sp_executesql @query;
It's long, but it should give you the same result. (dbfiddle demo)
If you are going the dynamic route, then just skip the pivoting and unpivoting.
– Jonathan Fite
8 hours ago
3
@JonathanFite I'm just showing an alternative way to do this and including the dynamic version with the PIVOT/UNPIVOT completed my answer.
– Taryn♦
8 hours ago
add a comment |
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = STUFF(
( SELECT ', ' + QUOTENAME(C.COLUMN_NAME) + ' AS ' + QUOTENAME(F.DESCRICAO)
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN TABBASE F ON C.COLUMN_NAME = F.NO_COL_TABBASE
WHERE C.TABLE_NAME = 'TABELA_ENTRADA'
ORDER BY C.ORDINAL_POSITION FOR XML PATH('')),1,2,'')
SELECT @SQL = 'SELECT ' + @SQL + ' FROM tabela_entrada'
PRINT @SQL
EXECUTE(@SQL)
jesus. Is there a better way than this? I didn't know i could use STUFF for this. I found this query on this microsoft page
I mean, the requirement itself is unreasonable. Column names should be a presentation layer issue. But yeah, it's dynamic SQL all the way if you absolutely need this to be done inside the engine.
– Jonathan Fite
8 hours ago
add a comment |
Your Answer
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "182"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f241656%2fis-it-possible-to-alias-a-column-based-on-the-result-of-a-selectwhere%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Sorry to say but your table structure is difficult to work with considering what you want to do. There are various ways you can probably get the result, one way would be to use UNPIVOT
and PIVOT
, but it's ugly.
You could start by UNPIVOT
ing the date in TB1
from your columns to rows:
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
This is going to return the data in the format of:
| COD | val | col |
|-----|------|------|
| 1 | cars | A001 |
| 1 | baby | A002 |
| 1 | nasa | A003 |
Then you could take that result and join it to TB2
:
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1;
Which gives the result:
| COD | val | DESCRIPTION |
|-----|------|-------------|
| 1 | cars | Something |
| 1 | baby | lasagna |
Now you have your new column names in the Description
and the val
in rows, but you want them in columns, so now you can apply the PIVOT
function to it:
select *
from
(
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1
) x
pivot
(
max(val)
for description in (Something, Lasagna)
) p;
This generates the final result you want:
| COD | Something | Lasagna |
|-----|-----------|---------|
| 1 | cars | baby |
Now all that is great if you know all the columns that you need to UNPIVOT
and then PIVOT
, but if you don't then you'll need to use dynamic SQL to solve it. Which will look something like this:
DECLARE
@colsUnpivot AS NVARCHAR(MAX),
@colsPivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsUnpivot
= stuff((select ','+quotename(C.column_name)
from information_schema.columns as C
where C.table_name = 'tb1' and
C.column_name like 'A%'
for xml path('')), 1, 1, '')
select @colsPivot
= stuff((select ','+quotename([DESCRIPTION])
from Tb2
for xml path('')), 1, 1, '')
set @query = 'select *
from
(
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in ('+ @colsUnpivot +')
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1
) x
pivot
(
max(val)
for description in ('+@colsPivot+')
) p;';
exec sp_executesql @query;
It's long, but it should give you the same result. (dbfiddle demo)
If you are going the dynamic route, then just skip the pivoting and unpivoting.
– Jonathan Fite
8 hours ago
3
@JonathanFite I'm just showing an alternative way to do this and including the dynamic version with the PIVOT/UNPIVOT completed my answer.
– Taryn♦
8 hours ago
add a comment |
Sorry to say but your table structure is difficult to work with considering what you want to do. There are various ways you can probably get the result, one way would be to use UNPIVOT
and PIVOT
, but it's ugly.
You could start by UNPIVOT
ing the date in TB1
from your columns to rows:
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
This is going to return the data in the format of:
| COD | val | col |
|-----|------|------|
| 1 | cars | A001 |
| 1 | baby | A002 |
| 1 | nasa | A003 |
Then you could take that result and join it to TB2
:
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1;
Which gives the result:
| COD | val | DESCRIPTION |
|-----|------|-------------|
| 1 | cars | Something |
| 1 | baby | lasagna |
Now you have your new column names in the Description
and the val
in rows, but you want them in columns, so now you can apply the PIVOT
function to it:
select *
from
(
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1
) x
pivot
(
max(val)
for description in (Something, Lasagna)
) p;
This generates the final result you want:
| COD | Something | Lasagna |
|-----|-----------|---------|
| 1 | cars | baby |
Now all that is great if you know all the columns that you need to UNPIVOT
and then PIVOT
, but if you don't then you'll need to use dynamic SQL to solve it. Which will look something like this:
DECLARE
@colsUnpivot AS NVARCHAR(MAX),
@colsPivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsUnpivot
= stuff((select ','+quotename(C.column_name)
from information_schema.columns as C
where C.table_name = 'tb1' and
C.column_name like 'A%'
for xml path('')), 1, 1, '')
select @colsPivot
= stuff((select ','+quotename([DESCRIPTION])
from Tb2
for xml path('')), 1, 1, '')
set @query = 'select *
from
(
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in ('+ @colsUnpivot +')
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1
) x
pivot
(
max(val)
for description in ('+@colsPivot+')
) p;';
exec sp_executesql @query;
It's long, but it should give you the same result. (dbfiddle demo)
If you are going the dynamic route, then just skip the pivoting and unpivoting.
– Jonathan Fite
8 hours ago
3
@JonathanFite I'm just showing an alternative way to do this and including the dynamic version with the PIVOT/UNPIVOT completed my answer.
– Taryn♦
8 hours ago
add a comment |
Sorry to say but your table structure is difficult to work with considering what you want to do. There are various ways you can probably get the result, one way would be to use UNPIVOT
and PIVOT
, but it's ugly.
You could start by UNPIVOT
ing the date in TB1
from your columns to rows:
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
This is going to return the data in the format of:
| COD | val | col |
|-----|------|------|
| 1 | cars | A001 |
| 1 | baby | A002 |
| 1 | nasa | A003 |
Then you could take that result and join it to TB2
:
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1;
Which gives the result:
| COD | val | DESCRIPTION |
|-----|------|-------------|
| 1 | cars | Something |
| 1 | baby | lasagna |
Now you have your new column names in the Description
and the val
in rows, but you want them in columns, so now you can apply the PIVOT
function to it:
select *
from
(
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1
) x
pivot
(
max(val)
for description in (Something, Lasagna)
) p;
This generates the final result you want:
| COD | Something | Lasagna |
|-----|-----------|---------|
| 1 | cars | baby |
Now all that is great if you know all the columns that you need to UNPIVOT
and then PIVOT
, but if you don't then you'll need to use dynamic SQL to solve it. Which will look something like this:
DECLARE
@colsUnpivot AS NVARCHAR(MAX),
@colsPivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsUnpivot
= stuff((select ','+quotename(C.column_name)
from information_schema.columns as C
where C.table_name = 'tb1' and
C.column_name like 'A%'
for xml path('')), 1, 1, '')
select @colsPivot
= stuff((select ','+quotename([DESCRIPTION])
from Tb2
for xml path('')), 1, 1, '')
set @query = 'select *
from
(
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in ('+ @colsUnpivot +')
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1
) x
pivot
(
max(val)
for description in ('+@colsPivot+')
) p;';
exec sp_executesql @query;
It's long, but it should give you the same result. (dbfiddle demo)
Sorry to say but your table structure is difficult to work with considering what you want to do. There are various ways you can probably get the result, one way would be to use UNPIVOT
and PIVOT
, but it's ugly.
You could start by UNPIVOT
ing the date in TB1
from your columns to rows:
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
This is going to return the data in the format of:
| COD | val | col |
|-----|------|------|
| 1 | cars | A001 |
| 1 | baby | A002 |
| 1 | nasa | A003 |
Then you could take that result and join it to TB2
:
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1;
Which gives the result:
| COD | val | DESCRIPTION |
|-----|------|-------------|
| 1 | cars | Something |
| 1 | baby | lasagna |
Now you have your new column names in the Description
and the val
in rows, but you want them in columns, so now you can apply the PIVOT
function to it:
select *
from
(
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in (A001, A002, A003)
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1
) x
pivot
(
max(val)
for description in (Something, Lasagna)
) p;
This generates the final result you want:
| COD | Something | Lasagna |
|-----|-----------|---------|
| 1 | cars | baby |
Now all that is great if you know all the columns that you need to UNPIVOT
and then PIVOT
, but if you don't then you'll need to use dynamic SQL to solve it. Which will look something like this:
DECLARE
@colsUnpivot AS NVARCHAR(MAX),
@colsPivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsUnpivot
= stuff((select ','+quotename(C.column_name)
from information_schema.columns as C
where C.table_name = 'tb1' and
C.column_name like 'A%'
for xml path('')), 1, 1, '')
select @colsPivot
= stuff((select ','+quotename([DESCRIPTION])
from Tb2
for xml path('')), 1, 1, '')
set @query = 'select *
from
(
select
d.COD,
d.val,
t2.DESCRIPTION
from
(
select *
from tb1 t1
unpivot
(
val
for col in ('+ @colsUnpivot +')
) u
)d
inner join tb2 t2
on d.col = t2.NO_COL_TB1
) x
pivot
(
max(val)
for description in ('+@colsPivot+')
) p;';
exec sp_executesql @query;
It's long, but it should give you the same result. (dbfiddle demo)
answered 8 hours ago
Taryn♦Taryn
7,3243 gold badges35 silver badges64 bronze badges
7,3243 gold badges35 silver badges64 bronze badges
If you are going the dynamic route, then just skip the pivoting and unpivoting.
– Jonathan Fite
8 hours ago
3
@JonathanFite I'm just showing an alternative way to do this and including the dynamic version with the PIVOT/UNPIVOT completed my answer.
– Taryn♦
8 hours ago
add a comment |
If you are going the dynamic route, then just skip the pivoting and unpivoting.
– Jonathan Fite
8 hours ago
3
@JonathanFite I'm just showing an alternative way to do this and including the dynamic version with the PIVOT/UNPIVOT completed my answer.
– Taryn♦
8 hours ago
If you are going the dynamic route, then just skip the pivoting and unpivoting.
– Jonathan Fite
8 hours ago
If you are going the dynamic route, then just skip the pivoting and unpivoting.
– Jonathan Fite
8 hours ago
3
3
@JonathanFite I'm just showing an alternative way to do this and including the dynamic version with the PIVOT/UNPIVOT completed my answer.
– Taryn♦
8 hours ago
@JonathanFite I'm just showing an alternative way to do this and including the dynamic version with the PIVOT/UNPIVOT completed my answer.
– Taryn♦
8 hours ago
add a comment |
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = STUFF(
( SELECT ', ' + QUOTENAME(C.COLUMN_NAME) + ' AS ' + QUOTENAME(F.DESCRICAO)
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN TABBASE F ON C.COLUMN_NAME = F.NO_COL_TABBASE
WHERE C.TABLE_NAME = 'TABELA_ENTRADA'
ORDER BY C.ORDINAL_POSITION FOR XML PATH('')),1,2,'')
SELECT @SQL = 'SELECT ' + @SQL + ' FROM tabela_entrada'
PRINT @SQL
EXECUTE(@SQL)
jesus. Is there a better way than this? I didn't know i could use STUFF for this. I found this query on this microsoft page
I mean, the requirement itself is unreasonable. Column names should be a presentation layer issue. But yeah, it's dynamic SQL all the way if you absolutely need this to be done inside the engine.
– Jonathan Fite
8 hours ago
add a comment |
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = STUFF(
( SELECT ', ' + QUOTENAME(C.COLUMN_NAME) + ' AS ' + QUOTENAME(F.DESCRICAO)
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN TABBASE F ON C.COLUMN_NAME = F.NO_COL_TABBASE
WHERE C.TABLE_NAME = 'TABELA_ENTRADA'
ORDER BY C.ORDINAL_POSITION FOR XML PATH('')),1,2,'')
SELECT @SQL = 'SELECT ' + @SQL + ' FROM tabela_entrada'
PRINT @SQL
EXECUTE(@SQL)
jesus. Is there a better way than this? I didn't know i could use STUFF for this. I found this query on this microsoft page
I mean, the requirement itself is unreasonable. Column names should be a presentation layer issue. But yeah, it's dynamic SQL all the way if you absolutely need this to be done inside the engine.
– Jonathan Fite
8 hours ago
add a comment |
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = STUFF(
( SELECT ', ' + QUOTENAME(C.COLUMN_NAME) + ' AS ' + QUOTENAME(F.DESCRICAO)
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN TABBASE F ON C.COLUMN_NAME = F.NO_COL_TABBASE
WHERE C.TABLE_NAME = 'TABELA_ENTRADA'
ORDER BY C.ORDINAL_POSITION FOR XML PATH('')),1,2,'')
SELECT @SQL = 'SELECT ' + @SQL + ' FROM tabela_entrada'
PRINT @SQL
EXECUTE(@SQL)
jesus. Is there a better way than this? I didn't know i could use STUFF for this. I found this query on this microsoft page
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = STUFF(
( SELECT ', ' + QUOTENAME(C.COLUMN_NAME) + ' AS ' + QUOTENAME(F.DESCRICAO)
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN TABBASE F ON C.COLUMN_NAME = F.NO_COL_TABBASE
WHERE C.TABLE_NAME = 'TABELA_ENTRADA'
ORDER BY C.ORDINAL_POSITION FOR XML PATH('')),1,2,'')
SELECT @SQL = 'SELECT ' + @SQL + ' FROM tabela_entrada'
PRINT @SQL
EXECUTE(@SQL)
jesus. Is there a better way than this? I didn't know i could use STUFF for this. I found this query on this microsoft page
answered 9 hours ago
Racer SQLRacer SQL
3,2424 gold badges28 silver badges68 bronze badges
3,2424 gold badges28 silver badges68 bronze badges
I mean, the requirement itself is unreasonable. Column names should be a presentation layer issue. But yeah, it's dynamic SQL all the way if you absolutely need this to be done inside the engine.
– Jonathan Fite
8 hours ago
add a comment |
I mean, the requirement itself is unreasonable. Column names should be a presentation layer issue. But yeah, it's dynamic SQL all the way if you absolutely need this to be done inside the engine.
– Jonathan Fite
8 hours ago
I mean, the requirement itself is unreasonable. Column names should be a presentation layer issue. But yeah, it's dynamic SQL all the way if you absolutely need this to be done inside the engine.
– Jonathan Fite
8 hours ago
I mean, the requirement itself is unreasonable. Column names should be a presentation layer issue. But yeah, it's dynamic SQL all the way if you absolutely need this to be done inside the engine.
– Jonathan Fite
8 hours ago
add a comment |
Thanks for contributing an answer to Database Administrators Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f241656%2fis-it-possible-to-alias-a-column-based-on-the-result-of-a-selectwhere%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Erik, The result would be the same as a "select * from tb1, but column names would be the
Description
from TB2. I will edit...I don't think its a case because I don't want to change the value of the result, I would like to change the "colum name" from TB1 based on a result from TB2. I would like to change the alias dynamically. TB1 has a column named A001, and on TB2 I have a descriptionA001 = Something
. Using this, I would like to use this value as a column name. I' trying using STUFF and I'm testing right now...– Racer SQL
9 hours ago
This feels like an EAV. Bad. Really bad. Dynamic SQL ( :( ) would be required.
– Michael Kutz
9 hours ago
2
Well, I don't know how "really bad" EAV is, but agree with Michael, dynamic SQL will be required.
– Aaron Bertrand♦
9 hours ago