SQL Server:使用子查询进行查询,包括从先前选择中进行选择

时间:2016-03-11 19:03:25

标签: sql sql-server

我试图在SQL Server中创建一个查询,以确定一个人的名字出现在列表中的次数,但该列表也是未知的,所以我必须得到实际的来自上一个选择索引的名称...很难解释,所以我先显示查询,希望有人可以提供帮助。

SELECT 
    SpeakerName, Spoken,
    (SELECT COUNT(SpeakerName)
     FROM tbl_SpeakerCard_Log
     WHERE SpeakerName = 'SpeakerName[i]' AND SpeakDate = '3-9-16') as TimesSpoken
FROM 
    tbl_SpeakerCard_Log
WHERE 
    AID = ####
ORDER BY 
    GeneralComment ASC

所以基本上,在SpeakerName[i]中,我想以某种方式从外部SpeakerName获取Select。输出应该是这样的

+-------------+--------+-------------+
| SpeakerName | Spoken | TimesSpoken |
+-------------+--------+-------------+
| Holly       |      0 |           4 |
| Robert      |      1 |           5 |
| Mike        |      1 |           2 |
+-------------+--------+-------------+

1 个答案:

答案 0 :(得分:0)

试试这个:

select x.SpeakerName, x.Spoken, COUNT(*) as TimesSpoken
from tbl_SpeakerCard_Log x
WHERE AID = ####
and x.SpeakDate = '3-9-16'
group by x.SpeakerName, x.Spoken

此计算机上未安装SSMS,因此无法对其进行测试。