我正在尝试选择不同的DP,RN并从结果中选择仅在表'EDate'=值中的另一个col的结果,然后在此之后获得行数。这是我到目前为止,但它不起作用..
SELECT
COUNT(*) AS eCount
FROM
(SELECT *
FROM
(SELECT DISTINCT
DP, RN
FROM
ECount
WHERE
DType = 'STRUCT')
WHERE
Month(EDate) = '07')) AS rows
如果建议我这样做,我无法将EDate
添加到Select Distinct
,因为我不希望这会弄乱我的不同选择。
例如
DP RN Edate
DP01 RN01 21/06/2017
DP01 RN01 22/07/2017
DP02 RN03 22/07/2017 yes
DP02 RN03 22/07/2017
DP01 RN04 22/07/2017 yes
DP02 RN05 22/07/2017 yes
DP03 RN06 22/07/2017 yes
结果应= 4
答案 0 :(得分:1)
您不能在外部查询中使用WHERE Month(EDate) = '07'
,因为EDate
不是内部查询的一部分。
尝试使用少一个派生表:
SELECT COUNT(*)
FROM
(
SELECT DISTINCT DP, RN
FROM ECount t0
WHERE DType = 'STRUCT'
AND Month(EDate) = 7
AND NOT EXISTS
(
SELECT 1
FROM ECount t1
WHERE t1.DP = t0.DP
AND t1.RN = t0.RN
AND t1.Month(EDate) <> 7
AND t1.DType = 'STRUCT' -- Not sure about this condition
)
) As rows
答案 1 :(得分:0)
;With Cte
As
(
Select
DP,
RN,
EDate,
Row_Number() Over(Partition By DP Order By RN Desc) As RowNum
From Example
Where Month(EDate) = 07
)
Select
DP,
RN,
EDate
From Cte
Where RowNum = 1
Order By DP;