Ich habe zwei Abfragen zu tun, wie untenWie Vereinigung mehrerer CTE
Abfrage 1
set @sql = cast(N'
;with cteSales as
(
select
datepart(weekday, s.enddate) as SalesWeekDay,
datediff(hour, cast(s.enddate as date), s.enddate) DayTime,
s.enddate SalesDate,
CONVERT(DECIMAL(10,2),OrigionalSubTotal/100.0) as OrigionalSubTotal,
o.ordertype ordertype
from sale s,DinePointOrderType o
where s.enddate >= @DateBegin and s.enddate < @DateEnd
and o.ordertypeindex = s.ordertype
and s.ordertype = 1
and s.IsSuspend = 0 and s.IsTrainMode = 0
and s.IsCancelled = 0 and s.wasrefunded=0
),
cteSalesPerWeekDays as
(
select
p.hrs,
p.period,
isnull(p.ordertype,''DINE IN'') ordertype,' as nvarchar(max)) + @col_per_day_list + N'
from #Timing t
cross join #WeekDays w
left join cteSales s on datediff(hour, w.wd_date, s.SalesDate) = t.hrs
pivot
(
Sum(s.OrigionalSubTotal)
for w.wd_name in (' + @pivot_val_per_day_list + N')
) p
)
select
r.hrs,
r.period as [From-To],
r.ordertype,' + @sum_cols_per_day_list + N'
from cteSalesPerWeekDays r
group by r.hrs, r.period,r.ordertype
order by r.hrs
'
exec sp_executesql @sql, N'@DateBegin datetime, @DateEnd datetime',
@DateBegin = @DateBegin,
@DateEnd = @TradeDateEnd
GO
Abfrage 2
set @sql = cast(N'
;with cteSales as
(
select
datepart(weekday, s.enddate) as SalesWeekDay,
datediff(hour, cast(s.enddate as date), s.enddate) DayTime,
s.enddate SalesDate,
CONVERT(DECIMAL(10,2),OrigionalSubTotal/100.0) as OrigionalSubTotal,
o.ordertype ordertype
from sale s,DinePointOrderType o
where s.enddate >= @DateBegin and s.enddate < @DateEnd
and o.ordertypeindex = s.ordertype
and s.ordertype = 2
and s.IsSuspend = 0 and s.IsTrainMode = 0
and s.IsCancelled = 0 and s.wasrefunded=0
),
cteSalesPerWeekDays as
(
select
p.hrs,
p.period,
isnull(p.ordertype,''TAKE OUT'') ordertype,' as nvarchar(max)) + @col_per_day_list + N'
from #Timing t
cross join #WeekDays w
left join cteSales s on datediff(hour, w.wd_date, s.SalesDate) = t.hrs
pivot
(
Sum(s.OrigionalSubTotal)
for w.wd_name in (' + @pivot_val_per_day_list + N')
) p
)
select
r.hrs,
r.period as [From-To],
r.ordertype,' + @sum_cols_per_day_list + N'
from cteSalesPerWeekDays r
group by r.hrs, r.period,r.ordertype
order by r.hrs
'
exec sp_executesql @sql, N'@DateBegin datetime, @DateEnd datetime',
@DateBegin = @DateBegin,
@DateEnd = @TradeDateEnd
Ist es möglich, eine Vereinigung zu tun diese zwei Abfragen?
Post Versuch, die UNION auszuführen, und welche Fehler Sie bekommen, so dass wir debug helfen deine Anstrengung. –
@TabAlleman hat meine Frage bearbeitet – Sachu
Der Grund für den Fehler ist, dass Sie Ihre erste 'CAST (' Funktion nach ''' Dine In''' schließen. Und Sie öffnen keine andere für' '' Take Out '' ' –