从一个表(即tblCases
),我可以根据给定日期间隔的ID对每个协议进行计数和分组:
ALTER PROCEDURE [dbo].[sp_CountAndGroupByProtocol]
(@startDate datetime, @endDate datetime)
AS
BEGIN
SELECT
COUNT(C.protocolID) AS total, protocolID
FROM
tblCases C
WHERE
C.dateOpened BETWEEN @startDate and @endDate
GROUP BY
C.protocolID
ORDER BY
total DESC
END
EXEC [dbo].[sp_CountAndGroupByProtocol] '2015-01-01', '2016-08-01'
我得到了正确的结果:
total protocolID
1 60 3860
2 43 5829
...
每个协议都与一位科学家相关联(即namePI
)。 tblProtocols
:
ID protocol_ID namePI
------------------------
1 3860 1
2 5829 5
..
tblPI
:
ID firstName lastName
------------------------
1 John Smith
2 Davis Emma
...
我想为每个协议添加此人的姓氏和名字:
total protocolID lastName firstName
---------------------------------------------------
1 60 3860 Smith John
2 43 5829 Davis Emma
...
我知道加入应该有效,但无论我把“加入”放在哪里,我都会
错误:JOIN附近的语法不正确
是因为我使用的是SQL Server吗?
我非常感谢社区的反馈。谢谢!
答案 0 :(得分:1)
这应该是您想要的,但如果您发布错误的代码,我们可能会给您一个确切的理由。
SELECT COUNT(C.protocolID) AS total, c.protocolID, lastName, firstName
FROM tblCases C
INNER JOIN tblProtocols P on P.Protocol_ID = C.ProtocolID
INNER JOIN tblPI PI on PI.ID = P.NamePI
WHERE C.dateOpened BETWEEN @startDate and @endDate
GROUP BY C.protocolID, lastName, firstName
ORDER BY total desc