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

时间:2018-08-24 11:58:25

标签: sql sql-server

我需要以下查询的帮助。我正在尝试计算计划消息和发送消息的数量,但查询输出未反映数据库中的数据

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 

运行查询时得到的内容

enter image description here

我想要实现的目标

enter image description here

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

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

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

WHERE子句的谓词只是将team.id与自身进行比较。您应该将其与id中的textmessage进行比较:

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

答案 1 :(得分:-1)

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