CTE内的CTE

yftpprvb  于 2022-10-22  发布在  其他
关注(0)|答案(2)|浏览(200)

是否可以在CTE中写入CTE?
我希望它遵循这个逻辑,但解释器不喜欢这个代码。

  1. with outertest as(
  2. with test as (
  3. select
  4. SRnum,
  5. gamenumber,
  6. StartOfDistribution,
  7. ApplicationNumber
  8. from #main
  9. where startofdistribution = '2011-06-14 00:00:00.000'
  10. and SRnum = '313'
  11. --order by SRnum, gamenumber, StartOfDistribution, ApplicationNumber
  12. )
  13. select
  14. ApplicationNumber
  15. ,count(*) as RetailerAppearance
  16. from test
  17. group by ApplicationNumber
  18. having count(*) = 4
  19. ) select count(*) from outertest
pw9qyyiw

pw9qyyiw1#

不能在SQL Server中这样嵌套CTE,但可以按以下方式使用多个CTE:

  1. ;with test as
  2. (
  3. select
  4. SRnum,
  5. gamenumber,
  6. StartOfDistribution,
  7. ApplicationNumber
  8. from #main
  9. where startofdistribution = '2011-06-14 00:00:00.000'
  10. and SRnum = '313'
  11. --order by SRnum, gamenumber, StartOfDistribution, ApplicationNumber
  12. ),
  13. outertest as
  14. (
  15. select
  16. ApplicationNumber
  17. ,count(*) as RetailerAppearance
  18. from test
  19. group by ApplicationNumber
  20. having count(*) = 4
  21. )
  22. select count(*)
  23. from outertest
展开查看全部
ogq8wdun

ogq8wdun2#

这实际上是可能的,只需对代码进行一些修改。只需在外部CTE之前添加一个选择
注:在Teradata工作良好

  1. with outertest as(
  2. SELECT * FROM (
  3. with test as (
  4. select
  5. SRnum,
  6. gamenumber,
  7. StartOfDistribution,
  8. ApplicationNumber
  9. from #main
  10. where startofdistribution = '2011-06-14 00:00:00.000'
  11. and SRnum = '313'
  12. --order by SRnum, gamenumber, StartOfDistribution, ApplicationNumber
  13. )
  14. select
  15. ApplicationNumber
  16. ,count(*) as RetailerAppearance
  17. from test
  18. group by ApplicationNumber
  19. having count(*) = 4 ) OUTER_CTE
  20. ) select count(*) from outertest
展开查看全部

相关问题