[英]How to get data from group by result set based on condition?
I am getting the data between 2 dates group by year and month.我正在按年和月获取 2 个日期组之间的数据。 Now for debugging purpose, I want to fetch check data from group result for a particular month but I am not getting how to do that.现在出于调试目的,我想从特定月份的组结果中获取检查数据,但我不知道如何做到这一点。
Query:询问:
SELECT CAST(MONTH(ActiveDate) AS VARCHAR(2)) + '-' + CAST(YEAR(ActiveDate) AS VARCHAR(4)) AS MyDate,
Count(*) AS Stats
FROM JobListings
where CompanyID = 100
and Status = 'Active'
and (ActiveDate >= '9/1/2020'
and ActiveDate <= '2/28/2021')
GROUP BY CAST(MONTH(ActiveDate) AS VARCHAR(2)) + '-' + CAST(YEAR(ActiveDate) AS VARCHAR(4))
This gives me the result like below:这给了我如下结果:
MyDate Stats
10-2020 3
11-2020 15
12 - 2020 4
and so on.
Now what I want is get the actual 3 records for "10-2020", so how do I inject a parent query to get the actual data from the group result set for particular month and year?现在我想要的是获取“10-2020”的实际 3 条记录,那么如何注入父查询以从特定月份和年份的组结果集中获取实际数据?
by this query, this should return only 3 records:通过这个查询,这应该只返回 3 条记录:
SELECT *
FROM JobListings
where
CompanyID = 100
and Status = 'Active'
and ActiveDate >= '10/01/2020'
and ActiveDate <= '11/01/2020'
well I add here instead of comments, try this and see what it returns:好吧,我在这里添加而不是评论,试试这个,看看它返回什么:
select *
, CAST(MONTH(ActiveDate) AS VARCHAR(2)) + '-' + CAST(YEAR(ActiveDate) AS VARCHAR(4)) Mydate
from JobListings
where CAST(MONTH(ActiveDate) AS VARCHAR(2)) + '-' + CAST(YEAR(ActiveDate) AS VARCHAR(4)) = '10-2020'
You need a window aggregate here, and no GROUP BY
.您在这里需要一个 window 聚合,并且没有GROUP BY
。
Also, I advise you to use EOMONTH
instead of splitting the date and casting like you have.另外,我建议您使用EOMONTH
而不是像您一样拆分日期和铸造。
SELECT
EOMONTH(ActiveDate),
Count(*) OVER (PARTITION BY EOMONTH(ActiveDate) AS Stats,
*
FROM JobListings
where
CompanyID = 100
and Status = 'Active'
and (ActiveDate >= '9/1/2020'
and ActiveDate <= '2/28/2021')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.