0

好的..这就是我想做的。我过度简化了下面的示例:-

我有一个表(Table1),其中包含如下引用:

Table1_ID (PK)

Table1_ID 说明

还有一张表(表2):-

Table2_ID (PK)

Table2_LinkedID (FK)

Table2_Status <--值为“打开”或“完成”

Table2_LinkedID 链接到 Table1_ID。

好的。现在我有三个要连接在一起的查询。这是我需要的。

第一个查询:-

SELECT * FROM Table1

这工作正常。

我想在查询中添加两个额外的列。第一个是Table2 中外键等于table1 的主键的记录总数(即SELECT *)。

第二个将是 Table2_Status = 'completed' 的记录计数

这有意义吗?

4

4 回答 4

2
select t1.Table1_ID, 
    t1.Table1_Description, 
    t2.TotalCount, 
    t2.CompletedCount
from Table1 t1
left outer join (
    select Table2_LinkedID, 
        count(*) as TotalCount,
        count(case when Table2_Status = 'completed' then 1 end) as CompletedCount
    from Table2
    group by Table2_LinkedID
) t2 on t1.Table1_ID = t2.Table2_LinkedID
于 2012-09-10T19:50:04.450 回答
1

GROUP BY你可以用聚合做一个简单的:

SELECT 
Table1.ID, 
Table1.Description,
Count(Table2.ID) AS TotalT2,
Sum(CASE WHEN Table2.Status = 'completed' THEN 1 ELSE 0 END) AS CountOfCompleted
FROM Table1
LEFT JOIN Table2 ON Table2.LinkedID = Table1.ID
GROUP BY Table1.ID, Table1.Description
于 2012-09-10T19:56:31.207 回答
1
SELECT t1.*,
(SELECT COUNT(*) FROM Table2 WHERE Table2_LinkedID = t1.ID) cntTotal,
(SELECT COUNT(*) FROM Table2 WHERE Table2_LinkedID = t1.ID AND Table2_Status = 'completed') cntCompleted
FROM Table1 t1

确保为外键设置适当的索引并Table2_Status获得最佳性能。

于 2012-09-10T19:50:20.000 回答
0

这对你有用吗?

查询一:

select a.ID
        , count(1) as Table2_RecordCount
from Table1 a
inner join Table2 b on b.LinkedID = a.ID
group by a.ID

查询 2:

select a.ID
        , count(1) as Table2_RecordCount
from Table1 a
inner join Table2 b on b.LinkedID = a.ID
where b.[Status] = 'completed'
group by a.ID
于 2012-09-10T20:37:45.893 回答