问题
I have a few tables that I am joining together and selecting various columns and sums from it and i want to combine the select statements so that all results are in the same results set. i currently have a query like:
declare @year INT
declare @month INT
set @year = '2013'
set @month = '08'
select CAST(LEFT(b.name, 3) AS varchar(3))AS Region, a.model, sum(a.Number)AS Uniques
from Table1 a
inner join database2.....table2 b
on a.code = b.code
where Year(a.EventDate) = @year
and Month(a.EventDate) = @month
and a.make='Toyota'
group by CAST(LEFT(b.name, 3) AS varchar(3)), a.model
order by CAST(LEFT(b.name, 3) AS varchar(3))
This brings up a dataset which looks something like:
Region Model Uniques
EST Toyota 200
EST Honda 350
CEN Toyota 220
CEN VW 150
I then have another similar query, but which uses different tables and requirements:
select CAST(LEFT(c.name, 3) AS varchar(3)) AS Region, a.Model, sum(b.Number)As Sales
from Table1 a
left join Table3 b
on a.leadid = b.leadid
inner join Database1..Table2 c
on a.code = c.code
where Year(a.EventDate) = @year
and Month(a.EventDate) = @month
and a.make='Toyota'
group by a.Model, CAST(LEFT(c.Name, 3) AS varchar(3))
order by CAST(LEFT(c.Name, 3) AS varchar(3))
this brings up a similar results set:
Region Model Sales
EST Toyota 150
CEN VW 80
CEN Toyota 75
I just want to pair these results or make a joined query so I can have results like;
Region Model Uniques Sales
EST Toyota 200 150
EST Honda 350 0
CEN Toyota 220 75
CEN vW 150 80
There are maybe 20-30 combinations of Region/Model that exist in total, and they are the same for each result set.
回答1:
Well, if you cannot do it all in one query, then you can simply join the 2 queries together:
select
t1.region,
t1.model,
t1.uniques,
t2.sales
from
(select CAST(LEFT(b.name, 3) AS varchar(3))AS Region, a.model, sum(a.Number)AS Uniques
from Table1 a
inner join database2.....table2 b
on a.code = b.code
where Year(a.EventDate) = @year
and Month(a.EventDate) = @month
and a.make='Toyota'
group by CAST(LEFT(b.name, 3) AS varchar(3)), a.model
order by CAST(LEFT(b.name, 3) AS varchar(3))
) t1
inner join
(
select CAST(LEFT(c.name, 3) AS varchar(3)) AS Region, a.Model, sum(b.Number)As Sales
from Table1 a
left join Table3 b
on a.leadid = b.leadid
inner join Database1..Table2 c
on a.code = c.code
where Year(a.EventDate) = @year
and Month(a.EventDate) = @month
and a.make='Toyota'
group by a.Model, CAST(LEFT(c.Name, 3) AS varchar(3))
order by CAST(LEFT(c.Name, 3) AS varchar(3))
) t2
on t1.region = t2.region
and t1.model = t2.model
回答2:
Use this concept:
SUM ( CASE WHEN ConditionIsMet THEN Column1 ELSE 0 END ),
SUM ( CASE WHEN OtherCondIsMet THEN Column2 ELSE 0 END )
来源:https://stackoverflow.com/questions/20530617/multiple-sums-with-different-where-clauses-in-same-query-result-set