CTE usage for two datasets

I want to know the best way to use the cte in this context where in I have 2 identical queries except for 2 different filter conditions .So below is how the definition of the cte with 2 different queries looks like at the moment .I will be using this two datasets separately in processing data .

with cte1

AS

(

select from table where a>1

)

with cte2

(

select from table where b>1

)

Is my declaration and definition right in this context or should it be 

with cte1

as

(

select from table where a>1

)

,

cte2

as

(

select from table where b>1

September 9th, 2015 4:23pm

CTEs can only be used in the immediate single statement accessing them. If you need both of them at the same time, then

;with cte1 as (select...), 

cte2 as (select ...)

select * from cte1 where Id not in (select .. from cte2) -- example of using both at once

If you need two separate statements each using its own cte, then

;with cte1 as (...)

select * from cte1;

;with cte2 as (...)

select * from cte2;

Free Windows Admin Tool Kit Click here and download it now
September 9th, 2015 4:40pm

I'm not sure you *need* CTE's for this.. you could just:

SELECT this, that, theOther
  FROM table
 WHERE this = that
UNION ALL
SELECT this, that, theOther
  FROM table
 WHERE this <> that

September 9th, 2015 4:51pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics