简体   繁体   中英

SQL Server 2008 R2: Concatenate alias name with column value

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 '+'.

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;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM