I have query like the following
select columns
from (select columns1
from result_set
where condition_common and condition1) as subset1
join
(select columns2
from result_set
where condition_common and condition2) as subset2
on subset1.somekey = subset2.somekey
I want to somehow reuse
select columns
from result_set
where condition_common
I have oversimplified the above query, but the above select in reality is huge and complicated. I dont want to have the burden of making sure both are in sync
I dont have any means of programmatically reusing it. T-SQL is ruled out. I can only write simple queries. This is an app limitation.
Is there a way to reuse same subquery, in a single statement
A subquery is a complete query that appears in the WHERE or HAVING clause of an SQL statement. You can specify up to 16 subqueries within a single SQL statement, and you can specify subqueries within a subquery. Subqueries run from last to first within the main SQL statement in which they appear.
You must enclose a subquery in parenthesis. A subquery must include a SELECT clause and a FROM clause. A subquery can include optional WHERE, GROUP BY, and HAVING clauses. A subquery cannot include COMPUTE or FOR BROWSE clauses.
A scalar subquery returns a single value (one column of one row). If no rows qualify to be returned, the subquery returns NULL. A non-scalar subquery returns 0, 1, or multiple rows, each of which may contain 1 or multiple columns. For each column, if there is no value to return, the subquery returns NULL.
To answer your question, Yes, you can have a subquery inside a Case statement.
Use a Common Table Expression (CTE) if you're using SQL Server 2005+:
with cte as (
select columns
from result_set
where condition_common
)
select columns
from cte as subset1
join
cte as subset2
on subset1.somekey = subset2.somekey
where otherconditions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With