我在这里有一些关于在子句中插入多个日期的问题。
以下是我通过互联网研究看到的代码。
;with cte (datelist, maxdate) as
(
select min(arrivaldate) datelist, max(departuredate) maxdate
from BookingsPerPerson
union all
select dateadd(dd, 1, datelist), maxdate
from cte
where datelist < maxdate
)
select c.datelist
into #tempDates
from cte c
select *
from
(
select b.person_id, b.arrivaldate, b.departuredate,
d.datelist,
convert(CHAR(10), datelist, 120) PivotDate
from #tempDates d
left join BookingsPerPerson b
on d.datelist between b.arrivaldate and b.departuredate
) x
pivot
(
count(datelist)
for PivotDate in ([2012-01-01], [2012-01-02], [2012-01-03],
[2012-01-04], [2012-01-05], [2012-01-06] , [2012-01-07])
) p;
由于代码是在 IN 子句中手动添加日期
pivot
(
count(datelist)
for PivotDate in ([2012-01-01], [2012-01-02], [2012-01-03],
[2012-01-04], [2012-01-05], [2012-01-06] , [2012-01-07])
) p;
我可以使用此代码提取/拆分的日期
;with cte (datelist, maxdate) as
(
select min(arrivaldate) datelist, max(departuredate) maxdate
from BookingsPerPerson
union all
select dateadd(dd, 1, datelist), maxdate
from cte
where datelist < maxdate
)
select c.datelist
into #tempDates
from cte c
在pivot语句中的“ IN ”子句中使用SELECT语句?
像这样?
pivot
(
count(datelist)
for PivotDate in (select c.datelist from #tempDates)
) p;
我试过这个,但它给了我一个错误?
有什么方法可以添加多个日期
临时表并将其包含在 IN 子句中?
你可以在这里尝试:http://sqlfiddle.com/#!3/8857c/9
答案 0 :(得分:0)
是的,有办法。首先将连接日期放在一个变量中..
例如:
DECLARE @dateArray AS VARCHAR(500)
SELECT @dateArray = '02 / 01 / 2014,02 / 02 / 2014,02 / 03 / 2014,02 / 04/2014'
然后创建一个动态的sql查询:
设置@query ='SELECT * FROM TABLE
PIVOT(count(datelist)PivotDate in('+ @dateArray +'))
希望它在某种程度上帮助了你。 :)