问题
I have Product
table with columns QtyID
, Qty
and Year_ID
. I also have a table tbl_Years
with ID
and Year
.
I have a simple SELECT
statement with SUM
calculation of Qty
:
SELECT
SUM(Qty) AS /*Sum_of_year_2016*/
FROM
Product p
INNER JOIN
tbl_Years ty ON p.Year_ID = ty.Year_ID
WHERE
ty.Year_ID = 6;
I want to define an alias name of Sum_of_year_2016
for the SUM(Qty)
value.
Note: the year should be fetched from the tbl_Years
table.
My attempt:
SELECT
SUM(Qty) AS 'Sum_of_year_' + ty.Year
FROM
Product p
INNER JOIN
tbl_Years ty ON p.Year_ID = ty.Year_ID
WHERE
ty.Year_ID = 6;
But I'm getting an error:
Syntax error; incorrect syntax near '+'.
回答1:
You need to use dynamic SQL to get custom alias:
DECLARE @year NVARCHAR(4) = (SELECT TOP 1 Year FROM tbl_Years WHERE Year_id=6);
DECLARE @sql NVARCHAR(MAX) =
'SELECT
SUM(Qty) AS ' + QUOTENAME('Sum_of_year_' + @year) +
' FROM Product p
INNER JOIN tbl_Years ty
ON p.Year_ID = ty.Year_ID
Where ty.Year_ID = 6;';
EXEC sp_executesql @sql;
来源:https://stackoverflow.com/questions/45706630/sql-server-2008-r2-concatenate-alias-name-with-column-value