sql - 显示来自另一个表

时间:2015-07-12 04:28:13

标签: sql sql-server sql-server-2008 sql-server-2008-r2

我有一个里程碑表: enter image description here

和状态表:

enter image description here

我有一个问题:

SELECT T1.Status,T2.MilestoneTitle FROM [Organisation].[dbo].[Status] T1
JOIN [Organisation].[dbo].[Milestone] T2 
ON T1.StatusId=T2.MilestoneStatusId WHERE T2.ProjectId=4

,输出为:

enter image description here

现在,我想将输出显示为:

enter image description here

如何为此编写查询?

2 个答案:

答案 0 :(得分:0)

通过使用Count和Group,我们可以实现这个目标

SELECT 
    T1.Status, COUNT(T2.MilestoneTitle) AS MilestoneTitleCount  
FROM 
    [Organisation].[dbo].[Status] T1
JOIN 
    [Organisation].[dbo].[Milestone] T2 ON T1.StatusId  = T2.MilestoneStatusId 
WHERE 
    T2.ProjectId = 4
GROUP BY 
    T1.Status
ORDER BY   
    T1.Status DESC

答案 1 :(得分:0)

SELECT Status, COUNT(MilestoneTitle) AS MilestoneTitleCount
FROM Organisation.dbo.Status  INNER JOIN
Organisation.dbo.Milestone  ON StatusId = MilestoneStatusId
WHERE (ProjectId = 4)
GROUP BY Status

COUNT()函数返回符合指定条件的行数

SELECT COUNT(column_name) FROM table_name;

GROUP BY语句与聚合函数结合使用,可以按一列或多列对结果集进行分组。

SELECT column_name, Count(column_name)
FROM table_name
WHERE <Confidtion>
GROUP BY column_name;