根据变量的值命名列

时间:2017-05-10 14:26:17

标签: sql sql-server

我有一个简单的查询,如下所示,工作正常。

但是,有两列没有显示如下所示的名称。我想根据变量@ date1&的值来命名列。 @ date2

isnull(t1.Quantity,0),isnull(t2.Quantity,0)

所以我会有类似的东西

isnull(t1.Quantity,0)[18-Apr-17],isnull(t2.Quantity,0)[19-Apr-17]

这可能吗?

我的查询

 declare @region nvarchar(10), @dateT1 date, @dateT2 date, @sd nvarchar(20)
 set @region= 'SF1611'
 set @dateT1 = '2017-04-18'
 set @dateT2 = '2017-04-19'
 set @sd = convert(nvarchar(20), @dateT1, 7)

;with t1 as
(
  select Id, Quantity  
  from myTable
  where Region = @region and dateQ = @dateT1
), t2 as 
(
  select Id, Quantity
  from myTable
  where Region = @region and dateQ = @dateT2
)
select coalesce(t1.Id, t2.Id) Id, isnull(t1.Quantity, 0), isnull(t2.Quantity,0), isnull(t1.Quantity, 0) - isnull(t2.Quantity,0) diff
from t1 full outer join t2
on t1.Id  = t2.Id
where isnull(t1.Quantity, 0) - isnull(t2.Quantity,0) <> 0

1 个答案:

答案 0 :(得分:2)

您可以使用dynamic SQL,在print

中发表评论之前,尝试EXEC结果以查看它是否是有效查询
 declare @regionnvarchar(10), @dateT1 date, @dateT2 date, @sd nvarchar(20)
 set @region= 'SF1611'
 set @dateT1 = '2017-04-18'
 set @dateT2 = '2017-04-19'
 set @sd = convert(nvarchar(20), @dateT1, 7)

;with t1 as
(
  select Id, Quantity  
  from myTable
  where Region = @region and dateQ = @dateT1
), t2 as 
(
  select Id, Quantity
  from myTable
  where Region = @region and dateQ = @dateT2
)


declare @SQL VARCHAR(max)

SET @SQL = 

'select coalesce(t1.Id, t2.Id) Id, isnull(t1.Quantity, 0) as ' + @dateT1 +', isnull(t2.Quantity,0) as ' +@dateT2 + ' ,(isnull(t1.Quantity, 0)- isnull(t2.Quantity,0)) as diff
from t1 full outer join t2
on t1.Id  = t2.Id
where isnull(t1.Quantity, 0) - isnull(t2.Quantity,0) <> 0'

print (@SQL)
--EXEC(@SQL)