本文介紹了SQL Server 2008 R2:將別名與列值連接起來的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有 Product
表,其中包含 QtyID
、Qty
和 Year_ID
列.我還有一個表 tbl_Years
帶有 ID
和 Year
.
I have Product
table with columns QtyID
, Qty
and Year_ID
. I also have a table tbl_Years
with ID
and Year
.
我有一個簡單的 SELECT
語句,其中 SUM
計算 Qty
:
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;
我想為 SUM(Qty)
值定義別名 Sum_of_year_2016
.
I want to define an alias name of Sum_of_year_2016
for the SUM(Qty)
value.
注意:應從 tbl_Years
表中獲取年份.
Note: the year should be fetched from the tbl_Years
table.
我的嘗試:
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;
但我收到一個錯誤:
語法錯誤;'+' 附近的語法不正確.
Syntax error; incorrect syntax near '+'.
推薦答案
需要使用動態SQL獲取自定義別名:
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;
這篇關于SQL Server 2008 R2:將別名與列值連接起來的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!