SQL选择拼图

时间:2012-09-10 19:46:33

标签: sql sql-server tsql

好的......这就是我想做的事情。我已经过度简化了以下示例: -

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

Table1_ID(PK)

表1_ID说明

还有另一张表(表2): -

Table2_ID(PK)

Table2_LinkedID(FK)

Table2_Status< - 值为“开放”或“完整”

Table2_LinkedID链接到Table1_ID。

确定。现在我有三个想要连接在一起的查询。这就是我需要的。

首先查询: -

SELECT * FROM Table1

这很好用。

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

第二个是Table2_Status ='completed'

的记录数

这有意义吗?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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提供适当的索引以获得最佳性能。

答案 2 :(得分: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

答案 3 :(得分:0)

这对你有用吗?

查询1:

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