使用SQL Server计算联合表中的行数

使用SQL Server计算联合表中的行数,sql,sql-server,Sql,Sql Server,我需要以下查询的帮助。我试图计算Schedule message和Send message的数量,但查询输出没有反映数据库中的数据 SQL查询 SELECT Max(dbo.team.teamname) AS teamname, Max(team.id) AS teamid, Max(teamlookup.id) AS TeamLockupId, (SELECT Count(team.id) F

我需要以下查询的帮助。我试图计算Schedule message和Send message的数量,但查询输出没有反映数据库中的数据

SQL查询

SELECT Max(dbo.team.teamname)         AS teamname,
   Max(team.id)                   AS teamid,
   Max(teamlookup.id)             AS TeamLockupId,
   (SELECT Count(team.id)
    FROM   textmessage
    WHERE  dontsendbefore IS NOT NULL
           AND team.id = team.id) AS CountSchedulemessage,
   (SELECT Count(team.id)
    FROM   textmessage
    WHERE  messagesent != 1
           AND team.id = team.id) AS CountSendMessage
 FROM   dbo.textmessage
   INNER JOIN dbo.teamlookup
           ON dbo.textmessage.teamlookupid = dbo.teamlookup.id
   INNER JOIN dbo.team
           ON dbo.teamlookup.teamid = dbo.team.id
GROUP  BY team.id 
运行查询时得到的信息

我希望实现的目标


感谢您的帮助

子查询的相关性似乎是错误的:

SELECT Max(dbo.team.teamname)         AS teamname,
   Max(team.id)                   AS teamid,
   Max(teamlookup.id)             AS TeamLockupId,
   (SELECT Count(team.id)
    FROM   textmessage t2
    WHERE  dontsendbefore IS NOT NULL
           AND t2.team.id = t.team.id) AS CountSchedulemessage,
   (SELECT Count(team.id)
    FROM   textmessage t3
    WHERE  messagesent != 1
       AND t3.team.id = t.team.id) AS CountSendMessage
 FROM   dbo.textmessage t
   INNER JOIN dbo.teamlookup
           ON dbo.textmessage.teamlookupid = dbo.teamlookup.id
   INNER JOIN dbo.team
           ON dbo.teamlookup.teamid = dbo.team.id
GROUP  BY team.id 
 (SELECT Count(team.id)
    FROM   textmessage
    WHERE  dontsendbefore IS NOT NULL
           AND team.id = team.id) AS CountSchedulemessage,
WHERE
子句的谓词只是将
team.id
与自身进行比较。您应该与
textmessage
id
进行比较:

 (SELECT Count(team.id)
    FROM   textmessage
    WHERE  dontsendbefore IS NOT NULL
           AND textmessage.team_id = team.id) AS CountSchedulemessage,

Tea.id=Studio ID。考虑使用别名;它将使您的代码更加简洁(并且更易于阅读)使用别名,这里我使用了t2和t3,否则team.id=team.id没有意义。