聚合函数作为多个表的列结果

时间:2018-01-30 21:19:56

标签: sql sql-server join left-join

我有以下表结构:

Table1
--------------
Table1Id
Field1
Field2

Table2
------------
Table2Id
Table1Id
Field1
Field2

Table3
-----------
Table3Id
Table1Id
Field1
Field2

我需要能够选择Table1中的所有字段,Table2中的记录数和Table3中的记录数。其中Table2中的记录数>表3中的记录数

以下是给定数据的预期输出示例:

Table1 Data
-------------
1     Record1Field1     Record1Feild2
2     Record2Field1     Record2Feild2
3     Record3Field1     Record3Feild2
4     Record4Field1     Record4Feild2 

Table2 Data
------------
1      1     Record1Field1     Record1Feild2
2      1     Record2Field1     Record2Feild2
3      2     Record3Field1     Record3Feild2
4      2     Record4Field1     Record4Feild2
5      2     Record5Field1     Record5Feild2
6      4     Record6Field1     Record6Feild2
7      4     Record6Field1     Record6Feild2
8      4     Record6Field1     Record6Feild2

Table3 Data
------------
1      2     Record1Field1     Record1Feild2   
2      2     Record2Field1     Record2Feild2   
3      3     Record3Field1     Record3Feild2   
4      3     Record4Field1     Record4Feild2   
5      3     Record5Field1     Record5Feild2   
6      4     Record6Field1     Record6Feild2   

期望的结果

Table1Id     Field1         Field2            Table2Count     Table3Count
1            Record1Field1  Record1Field2     2               0
2            Record2Field1  Recird2Field2     3               2
4            Record4Field1  Recird4Field2     3               1

表1中的通知记录3未显示,因为表2中的记录计数小于表3中的记录计数。我能够使用类似于下面的一个非常丑陋的查询来完成这项工作,但我觉得使用连接有更好的方法来实现这一点。

SELECT
    t1.Table1Id,
    t1.Field1,
    t1.Field2
    (Select Count(Table2Id) From Table2 t2 Where t2.Table1Id = t1.Table1Id) as Table2Count,
    (Select Count(Table3Id) From Table3 t3 Where t3.Table1Id = t1.Table1Id) as Table3Count,
From 
    Table1 t1
Where
    (Select Count(Table2Id) From Table2 t2 Where t2.Table1Id = t1.Table1Id)  >  (Select Count(Table3Id) From Table3 t3 Where t3.Table1Id = t1.Table1Id)

2 个答案:

答案 0 :(得分:0)

很难在没有工作示例的情况下对其进行测试,但这些方面的内容应该是一个很好的起点。

SELECT
    t1.Table1Id,
    t1.Field1,
    t1.Field2,
    COUNT(DISTINCT t2.Table2Id),
    COUNT(DISTINCT t3.Table3Id)
From Table1 t1 
    LEFT OUTER JOIN Table2 t2 ON t1.Table1Id = t2.Table1Id
    LEFT OUTER JOIN Table3 t3 ON t1.Table1Id = t3.Table1Id
GROUP BY t1.Table1Id
HAVING COUNT(DISTINCT t2.Table2Id) > COUNT(DISTINCT t3.Table3Id)

答案 1 :(得分:0)

你可以在t1中得到所有的值,并使用几个连接的分组值得到t2和t3的数据

SELECT
     t1.Table1Id
    ,t1.Field1
    ,t1.Field2
    , tt2.count_t2
    , tt3.count_t3
from table1 t1
join  (
  select Table1Id, count(*)  count_t2
  From Table2
  group by Table1Id
) tt2 on tt2.Table1Id  = t1.Table1Id
join  (
  select Table1Id, count(*)  count_t3
  From Table3
  group by Table1Id
) tt3 on tt3.Table1Id  = t1.Table1Id
where tt2.count_t2 < tt3.count_t3 <