创建复杂的报表查询时,除了递归之外,我发现CTE极其有用的一个地方。我使用一系列CTE获取所需的数据块,然后将其合并到最终选择中。我发现它们比使用大量派生表或20个联接执行相同的操作更容易维护,而且我发现由于在数据库中的一对多关系,我可以放心,它返回正确的数据而不会产生多条记录。所有不同的联接。让我举一个简单的例子:
;WITH Conferences (Conference_id)
AS
(select m.Conference_id
FROM mydb.dbo.Conference m
WHERE client_id = 10
and Conference_id in
(select Conference_id from mydb.dbo.Expense
where amount <>0
and amount is not null)
)
--select * from Conferences
,MealEaters(NumberMealEaters, Conference_id, AttendeeType)
AS
(Select count(*) as NumberMealEaters, m.Conference_id, AttendeeType
from mydb.dbo.attendance ma
join Conferences m on m.Conference_id = ma.Conference_id
where (ma.meals_consumed>0 or meals_consumed is null)and attended = 1
group by m.Conference_id)
--select * from MealEaters
,Expenses (Conference_id,expense_date, expenseDescription, RecordIdentifier,amount)
AS
(select Conference_id,max(expense_date) as Expense_date, expenseDescription, RecordIdentifier,sum(amount) as amount
FROM
(SELECT Conference_id,expense_date, amount, RecordIdentifier
FROM mydb.dbo.Expense
WHERE amount <> 0
and Conference_id IN
(SELECT Conference_id
FROM mydb.dbo.Conferences )
group by Conference_id, RecordIdentifier) a
)
--select * from Expenses
Select m.Conference_id,me.NumberMealEaters, me.AttendeeType, e.expense_date, e.RecordIdentifier,amount
from Conferences m
join mealeaters me on m.Conference_id = me.Conference_id
join expenses e on e.Conference_id = m.Conference_id
因此,通过分离出所需的不同信息块,您可以单独检查每个部分(使用注释掉的选择,通过单独取消对每个部分的注释,并且仅在选择的范围内运行),以及是否需要更改费用计算(在此示例中),要比将它们全部混合到一个大型查询中更容易找到。当然,我为此使用的实际报告查询通常比示例复杂得多。