简体   繁体   中英

SQL Count of results for each month in the Year

I have a SQL query, easy to get a single month.

But I am trying to write a stored procedure to get all the months.

DECLARE @datemin date = '2019-10-01';
DECLARE @maxdate date = '2019-12-31' 

WHILE @datemin <= @maxdate 
BEGIN
    SELECT DISTINCT
        A.sMonth, A.sYear, COUNT(*)
    FROM
        ClientsTable A
    CROSS APPLY 
        [dbo].[udfdob] (A.[DateOfBirth], @maxdate) B
    WHERE 
        sDate BETWEEN @datemin AND @maxdate
    GROUP BY   
        A.sMonth, A.sYear

    SET @datemin = DATEADD(MONTH, 1, @datemin) 
END

--EXEC sp_clientWaiting

but the output appears multiple times:

在此处输入图像描述

How do I go about to get the result for every month in the year just once?

Currently I am having to type the dates manually for each month.

Thanks in advance.

Remove the WHILE

    DECLARE @datemin date = '2019-10-01';
    DECLARE @maxdate date = '2019-12-31' 


    SELECT
        A.sMonth, A.sYear, COUNT(*)
    FROM
        ClientsTable A
    CROSS APPLY 
        [dbo].[udfdob] (A.[DateOfBirth], @maxdate) B
    WHERE 
        sDate BETWEEN @datemin AND @maxdate
    GROUP BY   
        A.sMonth, A.sYear



From what you say it looks like the first time the loop runs, it's what you want. Every other iteration of the loop is just the first result set with yet another row removed

You don't need DISTINCT if you're GROUPing

Do you use the output of the udfdob function? It doesn't seem to appear in the query, so it's only effect would be if it were returning a resultset of multiple rows but it doesn't feel like it does...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM