在我的SQL结束时,我使用以下代码。有没有办法将固定字符串[2011/07/14],[2011/07/16]等替换为GetDate()值?
PIVOT
(
count([AppointmentsBooked])
FOR [date] IN ([2011/07/14], [2011/07/16], [2011/07/17],[2011/07/18],[2011/07/21])
) as pivottable
答案 0 :(得分:0)
您可以尝试以下列方式使用BETWEEN
和DATEADD
:
DECLARE @dates TABLE(value DateTime)
INSERT INTO @dates VALUES
(GETDATE()),
('2011/07/9'),
('2011/07/17'),
('2011/07/18'),
('2011/07/21')
SELECT value FROM @dates
WHERE value BETWEEN GETDATE() AND DATEADD(day, 5, GETDATE())
答案 1 :(得分:0)
您可以创建一个包含所有日期的字符串,这些日期在每个日期之前和之后用'['和']'逗号分隔。将此字符串分配给字符串变量(@dates)并使用字符串spit方法拆分透视查询中的所有日期。
答案 2 :(得分:0)
这个问题大约在一年前发布。我不在乎。我有一些代码可能正是OP想要的....我敢肯定他永远不会回来并选择一个答案但仍然......我想做的就是按月计算记录数对于几个表并最终比较每个表的每个月的记录数。但是......在这段代码中只有一个表(rt_taco_15m),但这并不重要。我还没写完其余内容以完全符合我的需求。但我认为这符合OP的需要,或者至少让他有一个良好的开端......如果他真的已经等了一年才能解决这个问题。大声笑。
if object_id('tempdb..#temp') is not null drop table #temp
if object_id('tempdb..#temp2') is not null drop table #temp2
if object_id('tempdb..#temp3') is not null drop table #temp3
declare @start_date as datetime
set @start_date = cast('1-1-2012' as datetime)
declare @end_date as datetime
set @end_date = cast('9-1-2012' as datetime)
;with cte as (
select @start_date as [start],
dateadd(month, 1, @start_date) as [end]
union all
select dateadd(month, 1, [start]) as [start],
dateadd(month, 1, dateadd(month, 1, [start])) as [end]
from cte
where dateadd(month, 1, [start]) <= @end_date
)
(select 'rt_taco_15m' as table_name,
convert(varchar(10), [start], 101) as [start],
convert(varchar(10), [end], 101) as [end],
datename(month, [start]) as month_name,
cast([start] as integer) as orderby,
count(taco.taco_record_id) as [range_count]
into #temp
from cte
left outer join rt_taco_15m as taco
on taco.period >= cte.[start] and
taco.period < cte.[end]
group by cte.[start], cte.[end])
select table_name as table_name,
convert(varchar(10), getdate(), 101) as [start],
convert(varchar(10), getdate(), 101) as [end],
'Total' as month_name,
cast(dateadd(month,2,@end_date) as integer) as orderby,
range_sum as [range_count]
into #temp2
from (select table_name, sum([range_count]) as range_sum
from #temp group by table_name) as summed_up
select *
into #temp3
from (select * from #temp
union all
select * from #temp2) as x
order by orderby
select * from #temp3
declare @cols nvarchar(2000)
select @cols = stuff(
(select '],[' + month_name
from #temp3
order by orderby
for xml path('') )
, 1, 2, '') + ']'
print @cols
if object_id('tempdb..#temp2') is not null drop table #temp2
declare @query varchar(max)
set @query = N'
select table_name, ' + @cols + N'
from (select table_name, month_name, range_count
from #temp3) p
pivot ( sum(range_count) for month_name in ( '+ @cols +' ) ) as pvt'
execute(@query