我试图通过计算另一个子查询返回的行来加入子查询计数。 我的问题是我不知道是否/如何公开REP_ID(使用MONTH_COUNT)加入我的主要查询。
INNER JOIN
(SELECT COUNT(*) AS MONTH_COUNT
FROM
(
SELECT REP_ID, COUNT(MONTH(COMP_DT)) AS COUNT_
FROM dattbl_Case AS MONTH_
WHERE (CASE_TYPE=@CASE_TYPE) AND COMP_DT > DATEADD(MONTH,-12,GETDATE()) AND COMP_DT <= DATEADD(MONTH,-1,GETDATE())
GROUP BY MONTH(COMP_DT), REP_ID
) AS MONTH__
) AS MONTHS_
ON EXPIRE_.REP_ID=?
答案 0 :(得分:1)
我想你想要这个:
INNER JOIN
(SELECT REP_ID, COUNT(DISTINCT MONTH(COMP_DT)) AS COUNT_
FROM dattbl_Case AS MONTH_
WHERE CASE_TYPE = @CASE_TYPE AND COMP_DT > DATEADD(MONTH, -12, GETDATE()) AND
COMP_DT <= DATEADD(MONTH,-1,GETDATE())
GROUP BY REP_ID
) AS MONTHS_
ON EXPIRE_.REP_ID = MONTHS_.REP_ID
这个表述假定月份都在同一年内。如果您希望计数大于12,则需要包括年份和月份。
答案 1 :(得分:0)
以下是更正的解决方案。我只是没有将子查询公开给父子查询,然后加入主查询。
INNER JOIN
(SELECT MONTH__.REP_ID, COUNT(*) AS MONTH_COUNT
FROM
(
SELECT MONTH_.REP_ID, COUNT(MONTH(COMP_DT)) AS COUNT_
FROM dattbl_Case AS MONTH_
WHERE (CASE_TYPE=@CASE_TYPE) AND COMP_DT > DATEADD(MONTH,-12,GETDATE()) AND COMP_DT <= DATEADD(MONTH,-1,GETDATE())
GROUP BY MONTH(COMP_DT), REP_ID
) AS MONTH__
GROUP BY MONTH__.REP_ID
) AS MONTHS_
ON EXPIRE_.REP_ID=MONTHS_.REP_ID