我需要以下查询的帮助。我正在尝试计算计划消息和发送消息的数量,但查询输出未反映数据库中的数据
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
运行查询时得到的内容
我想要实现的目标
感谢您的帮助
答案 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