Link to home
Start Free TrialLog in
Avatar of chudmarek
chudmarek

asked on

Join 2 Queries

Hi Guys,

I want to be able to combine two queries into 1 result set.

I have for example:

QUERY 1:
Select Distinct Name,Count(*) AS TotalCount
FROM Table1
WHERE
Condition1 > 0
Group BY Name
ORDER BY Name

QUERY2:

Select Distinct Name,Count(*) AS TotalCountWithCondition
FROM Table1
WHERE
Condition1 > 0
AND Condtion2 = 0
Group BY Name
ORDER BY Name

So basically query2 is a subset of Query1 with the extra condition "AND Condition2=0"

I want this to be displayed as 1 returned set, say with column headers like

Name|TotalCount|TotalCountWithCondition


Thanks in advance.
Avatar of Dan Craciun
Dan Craciun
Flag of Romania image

Normally you would UNION the results, don't know how well will this work with DISTINCT:
Select Distinct Name,Count(*) AS TotalCount
FROM Table1
WHERE 
Condition1 > 0
Group BY Name
ORDER BY Name
UNION
Select Count(*) AS TotalCountWithCondition
FROM Table1
WHERE 
Condition1 > 0
AND Condtion2 = 0 
Group BY Name
ORDER BY Name

Open in new window

Avatar of Rgonzo1971
Rgonzo1971

HI,

pls try

SELECT T1.Name, T1.TotalCount, T2.TotalCountWithCondition
FROM(
SELECT Name, Count(Name) AS TotalCount, Condition1
FROM Table1
GROUP BY Name, Condition1
HAVING Condition1>0) as T1 LEFT JOIN (SELECT Name, Count(Name) AS TotalCountWithCondition
FROM Table1
GROUP BY Name, Condition1, Condition2
HAVING Condition1>0 AND Condition2=0) AS T2 ON T1.Name = T2.Name

Open in new window

Regards
ASKER CERTIFIED SOLUTION
Avatar of skullnobrains
skullnobrains

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
select distinct
....
group by
....

WRONG

You NEVER need to add "distinct" if you are using a group by clause.

and,
 I would choose skullnobrains to write this query :)