如何在一个SQL查询中从几个表中计算相同的列
我有五张桌子,TDetective,TMonths,TProduct1,TProduct2和TProduct3。我想要一个包含四列的结果集:如何在一个SQL查询中从几个表中计算相同的列,sql,Sql,我有五张桌子,TDetective,TMonths,TProduct1,TProduct2和TProduct3。我想要一个包含四列的结果集: 首先是侦探的名字 第二个是计数-在特殊月份分配给这个侦探多少个TProduct1 第三个是计数-在特殊月份分配给这个侦探多少个TProduct2 第四个是计数——在特殊的月份里,有多少TProduct3分配给了这个侦探 请帮帮我 TDetective |id | |Detective| 三个月 |id |
- 首先是侦探的名字
- 第二个是计数-在特殊月份分配给这个侦探多少个TProduct1
- 第三个是计数-在特殊月份分配给这个侦探多少个TProduct2
- 第四个是计数——在特殊的月份里,有多少TProduct3分配给了这个侦探
|id |
|Detective|
三个月
|id |
|Months |
产品1
|id |
|RequestDay|
|Mobile|
|Operator|
|Subjects|
|OccurrenceMode|
|Detective|
|Months|
产品2
|id |
|RequestDay|
|Mobile|
|Operator|
|Subjects|
|OccurrenceMode|
|Detective|
|Months|
产品3
|id |
|RequestDay|
|Mobile|
|Operator|
|Subjects|
|OccurrenceMode|
|Detective|
|Months|
我的SQL查询如下所示:
select
TDetective.Detective,
count(TProduct1.id) as countOfDetectiveP1
count(TProduct2.id) as countOfDetectiveP2
count(TProduct3.id) as countOfDetectiveP3
from
TDetective
left outer join
TProduct1 on TDetective.Detective = TProduct1.Detective
where
TProduct1.Months in (select months from TMonths)
left outer join
TProduct2 on TDetective.Detective = TProduct2.Detective
where
TProduct2.Months in (select months from TMonths)
left outer join
TProduct3 on TDetective.Detective = TProduct3.Detective
where
TProduct3.Months in (select months from TMonths)
group by
Detective.Detective
order by
Detective
非常感谢我会交叉加入前两个表,以获得每个月的一行。然后使用相关子查询填写其余信息:
select d.id, d.month,
(select count(*)
from product1 p1
where p1.detective = d.id and
p1.month = m.month
),
(select count(*)
from product2 p2
where p2.detective = d.id and
p2.month = m.month
),
(select count(*)
from product3 p3
where p3.detective = d.id and
p3.month = m.month
)
from detective d cross join
months m;
您可以在外部查询中添加
where
子句,以筛选特定的侦探或月份。将where
替换为和
。使用正在使用的数据库标记您的问题。
select d.Detective,
(select count(*)
from P118 p1
where p1.detective = d.Detective and
p1.Months in (select months from TempMonths)
),
(select count(*)
from P119 p2
where p2.detective = d.Detective and
p2.Months in (select months from TempMonths)
),
(select count(*)
from P120 p3
where p3.detective = d.Detective and
p3.Months in (select months from TempMonths)
)
from Detective d
order by Detective