SQL Server 2008 R2: Concatenate alias name with column value

强颜欢笑 提交于 2021-01-28 00:01:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!