SQL Server: retrieve unique rows for a specific year but not if they are created earlier












0














I have a query that shows a list of products in the year 2018.



I want to view the products if they are created uniquely in 2018 and should not be shown if they have been created earlier in for example in 2017 or so.



Here is my SQL:



CREATE TABLE [dbo].[Products]
(
[GTIN] [VARCHAR](50) NULL,
[Location] [INT] NULL,
[Date] [DATETIME] NULL
) ON [PRIMARY]
GO

INSERT INTO Products123(GTIN, Location, Date)
VALUES (12345678911, 1, '2017-01-01 00:00:00.000'),
(12345678911, 1, '2018-01-01 00:00:00.000'),
(12345678912, 1, '2018-02-01 00:00:00.000'),
(12345678913, 1, '2018-03-01 00:00:00.000'),
(12345678914, 1, '2018-03-01 00:00:00.000'),
(12345678915, 1, '2018-04-01 00:00:00.000'),
(12345678916, 1, '2018-05-01 00:00:00.000'),
(12345678917, 1, '2018-06-01 00:00:00.000'),
(12345678918, 1, '2018-07-01 00:00:00.000');


My query:



SELECT 
DATENAME(MONTH, DATE) AS Dato,
COUNT(DISTINCT GTIN) AS PRODUCTS
FROM
(SELECT
GTIN, DATE = MIN(DATE)
FROM
Products
WHERE
YEAR(DATE) = '2018'
AND YEAR(DATE) NOT IN (2017)
GROUP BY
GTIN) d
GROUP BY
MONTH(DATE), DATENAME(MONTH, DATE)
ORDER BY
MONTH(DATE)


Result:



Dato    |   Products
January | 1
February| 1
April | 2
May | 1
June | 1
July | 1


Expected Result:



Dato    |   Products
January | 0
February| 1
April | 2
May | 1
June | 1
July | 1


January should be Zero since the product is already created in 2017 (or earlier) and therefore not unique anymore. Can someone help how retrieve the correct list










share|improve this question





























    0














    I have a query that shows a list of products in the year 2018.



    I want to view the products if they are created uniquely in 2018 and should not be shown if they have been created earlier in for example in 2017 or so.



    Here is my SQL:



    CREATE TABLE [dbo].[Products]
    (
    [GTIN] [VARCHAR](50) NULL,
    [Location] [INT] NULL,
    [Date] [DATETIME] NULL
    ) ON [PRIMARY]
    GO

    INSERT INTO Products123(GTIN, Location, Date)
    VALUES (12345678911, 1, '2017-01-01 00:00:00.000'),
    (12345678911, 1, '2018-01-01 00:00:00.000'),
    (12345678912, 1, '2018-02-01 00:00:00.000'),
    (12345678913, 1, '2018-03-01 00:00:00.000'),
    (12345678914, 1, '2018-03-01 00:00:00.000'),
    (12345678915, 1, '2018-04-01 00:00:00.000'),
    (12345678916, 1, '2018-05-01 00:00:00.000'),
    (12345678917, 1, '2018-06-01 00:00:00.000'),
    (12345678918, 1, '2018-07-01 00:00:00.000');


    My query:



    SELECT 
    DATENAME(MONTH, DATE) AS Dato,
    COUNT(DISTINCT GTIN) AS PRODUCTS
    FROM
    (SELECT
    GTIN, DATE = MIN(DATE)
    FROM
    Products
    WHERE
    YEAR(DATE) = '2018'
    AND YEAR(DATE) NOT IN (2017)
    GROUP BY
    GTIN) d
    GROUP BY
    MONTH(DATE), DATENAME(MONTH, DATE)
    ORDER BY
    MONTH(DATE)


    Result:



    Dato    |   Products
    January | 1
    February| 1
    April | 2
    May | 1
    June | 1
    July | 1


    Expected Result:



    Dato    |   Products
    January | 0
    February| 1
    April | 2
    May | 1
    June | 1
    July | 1


    January should be Zero since the product is already created in 2017 (or earlier) and therefore not unique anymore. Can someone help how retrieve the correct list










    share|improve this question



























      0












      0








      0







      I have a query that shows a list of products in the year 2018.



      I want to view the products if they are created uniquely in 2018 and should not be shown if they have been created earlier in for example in 2017 or so.



      Here is my SQL:



      CREATE TABLE [dbo].[Products]
      (
      [GTIN] [VARCHAR](50) NULL,
      [Location] [INT] NULL,
      [Date] [DATETIME] NULL
      ) ON [PRIMARY]
      GO

      INSERT INTO Products123(GTIN, Location, Date)
      VALUES (12345678911, 1, '2017-01-01 00:00:00.000'),
      (12345678911, 1, '2018-01-01 00:00:00.000'),
      (12345678912, 1, '2018-02-01 00:00:00.000'),
      (12345678913, 1, '2018-03-01 00:00:00.000'),
      (12345678914, 1, '2018-03-01 00:00:00.000'),
      (12345678915, 1, '2018-04-01 00:00:00.000'),
      (12345678916, 1, '2018-05-01 00:00:00.000'),
      (12345678917, 1, '2018-06-01 00:00:00.000'),
      (12345678918, 1, '2018-07-01 00:00:00.000');


      My query:



      SELECT 
      DATENAME(MONTH, DATE) AS Dato,
      COUNT(DISTINCT GTIN) AS PRODUCTS
      FROM
      (SELECT
      GTIN, DATE = MIN(DATE)
      FROM
      Products
      WHERE
      YEAR(DATE) = '2018'
      AND YEAR(DATE) NOT IN (2017)
      GROUP BY
      GTIN) d
      GROUP BY
      MONTH(DATE), DATENAME(MONTH, DATE)
      ORDER BY
      MONTH(DATE)


      Result:



      Dato    |   Products
      January | 1
      February| 1
      April | 2
      May | 1
      June | 1
      July | 1


      Expected Result:



      Dato    |   Products
      January | 0
      February| 1
      April | 2
      May | 1
      June | 1
      July | 1


      January should be Zero since the product is already created in 2017 (or earlier) and therefore not unique anymore. Can someone help how retrieve the correct list










      share|improve this question















      I have a query that shows a list of products in the year 2018.



      I want to view the products if they are created uniquely in 2018 and should not be shown if they have been created earlier in for example in 2017 or so.



      Here is my SQL:



      CREATE TABLE [dbo].[Products]
      (
      [GTIN] [VARCHAR](50) NULL,
      [Location] [INT] NULL,
      [Date] [DATETIME] NULL
      ) ON [PRIMARY]
      GO

      INSERT INTO Products123(GTIN, Location, Date)
      VALUES (12345678911, 1, '2017-01-01 00:00:00.000'),
      (12345678911, 1, '2018-01-01 00:00:00.000'),
      (12345678912, 1, '2018-02-01 00:00:00.000'),
      (12345678913, 1, '2018-03-01 00:00:00.000'),
      (12345678914, 1, '2018-03-01 00:00:00.000'),
      (12345678915, 1, '2018-04-01 00:00:00.000'),
      (12345678916, 1, '2018-05-01 00:00:00.000'),
      (12345678917, 1, '2018-06-01 00:00:00.000'),
      (12345678918, 1, '2018-07-01 00:00:00.000');


      My query:



      SELECT 
      DATENAME(MONTH, DATE) AS Dato,
      COUNT(DISTINCT GTIN) AS PRODUCTS
      FROM
      (SELECT
      GTIN, DATE = MIN(DATE)
      FROM
      Products
      WHERE
      YEAR(DATE) = '2018'
      AND YEAR(DATE) NOT IN (2017)
      GROUP BY
      GTIN) d
      GROUP BY
      MONTH(DATE), DATENAME(MONTH, DATE)
      ORDER BY
      MONTH(DATE)


      Result:



      Dato    |   Products
      January | 1
      February| 1
      April | 2
      May | 1
      June | 1
      July | 1


      Expected Result:



      Dato    |   Products
      January | 0
      February| 1
      April | 2
      May | 1
      June | 1
      July | 1


      January should be Zero since the product is already created in 2017 (or earlier) and therefore not unique anymore. Can someone help how retrieve the correct list







      sql-server date count






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 23 '18 at 14:21









      marc_s

      571k12811031251




      571k12811031251










      asked Nov 23 '18 at 13:40









      MishMish

      317313




      317313
























          2 Answers
          2






          active

          oldest

          votes


















          1














          You could simply use NOT EXISTS:



          WITH products2018 AS (
          SELECT *
          FROM @Products AS p
          WHERE Date >= '2018-01-01'
          AND NOT EXISTS (
          SELECT *
          FROM @Products AS x
          WHERE GTIN = p.GTIN
          AND Date < '2018-01-01'
          )
          )
          SELECT DATENAME(MONTH, d), COUNT(products2018.GTIN)
          FROM (VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11)) AS numbers(n)
          CROSS APPLY (SELECT DATEADD(MONTH, n, '2018-01-01')) AS dates(d)
          LEFT JOIN products2018 ON YEAR(products2018.Date) = YEAR(d) AND MONTH(products2018.Date) = MONTH(d)
          GROUP BY d
          ORDER BY d





          share|improve this answer























          • Hello Salman What about DATE = min(DATE)? I'm actually Getting more values in 2018 and that's wrong, it should be less.
            – MishMish
            Nov 23 '18 at 14:04










          • It seems to work for your posted data. Cannot tell where it is coming from but you can comment out the group by / count(*) to debug.
            – Salman A
            Nov 23 '18 at 14:07










          • I'm applying it to my live data which im working with, the difference is the WHERE Clause has just more sql in it. But the numbers are higher than expected, and yes it does work correctly with the above code, so can't tell what's wrong yet :(
            – MishMish
            Nov 23 '18 at 14:13










          • If my where clause has more sql, then it should be writen in both where clauses in your example right? here is an Image of how it looks like: prnt.sc/lm280r
            – MishMish
            Nov 23 '18 at 14:16










          • I think you can probably discard everything after 2018 in the not exists query (the only check is that the product did not exist before 2018). But I am not sure.
            – Salman A
            Nov 23 '18 at 14:20



















          0














          This uses a Calendar Table instead, but perhaps this get's you what you are after?



          WITH CTE AS(
          SELECT CT.CalendarDate,
          CT.CalendarMonth,
          CT.CalendarMonthName,
          P.GTIN,
          P.[Location],
          P.[Date],
          MIN(P.[date]) OVER (PARTITION BY P.GTIN) AS MinDate
          FROM dbo.CalendarTable CT
          LEFT JOIN dbo.Products P ON CT.CalendarDate = P.[date]
          WHERE CT.CalendarYear IN (2017,2018))
          SELECT CTE.CalendarMonth,
          CTE.CalendarMonthName,
          COUNT(DISTINCT CASE WHEN CTE.MinDate > '20180101' THEN CTE.GTIN END) AS Products
          FROM CTE
          GROUP BY CTE.CalendarMonth,
          CTE.CalendarMonthName
          ORDER BY CTE.CalendarMonth;





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447787%2fsql-server-retrieve-unique-rows-for-a-specific-year-but-not-if-they-are-created%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You could simply use NOT EXISTS:



            WITH products2018 AS (
            SELECT *
            FROM @Products AS p
            WHERE Date >= '2018-01-01'
            AND NOT EXISTS (
            SELECT *
            FROM @Products AS x
            WHERE GTIN = p.GTIN
            AND Date < '2018-01-01'
            )
            )
            SELECT DATENAME(MONTH, d), COUNT(products2018.GTIN)
            FROM (VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11)) AS numbers(n)
            CROSS APPLY (SELECT DATEADD(MONTH, n, '2018-01-01')) AS dates(d)
            LEFT JOIN products2018 ON YEAR(products2018.Date) = YEAR(d) AND MONTH(products2018.Date) = MONTH(d)
            GROUP BY d
            ORDER BY d





            share|improve this answer























            • Hello Salman What about DATE = min(DATE)? I'm actually Getting more values in 2018 and that's wrong, it should be less.
              – MishMish
              Nov 23 '18 at 14:04










            • It seems to work for your posted data. Cannot tell where it is coming from but you can comment out the group by / count(*) to debug.
              – Salman A
              Nov 23 '18 at 14:07










            • I'm applying it to my live data which im working with, the difference is the WHERE Clause has just more sql in it. But the numbers are higher than expected, and yes it does work correctly with the above code, so can't tell what's wrong yet :(
              – MishMish
              Nov 23 '18 at 14:13










            • If my where clause has more sql, then it should be writen in both where clauses in your example right? here is an Image of how it looks like: prnt.sc/lm280r
              – MishMish
              Nov 23 '18 at 14:16










            • I think you can probably discard everything after 2018 in the not exists query (the only check is that the product did not exist before 2018). But I am not sure.
              – Salman A
              Nov 23 '18 at 14:20
















            1














            You could simply use NOT EXISTS:



            WITH products2018 AS (
            SELECT *
            FROM @Products AS p
            WHERE Date >= '2018-01-01'
            AND NOT EXISTS (
            SELECT *
            FROM @Products AS x
            WHERE GTIN = p.GTIN
            AND Date < '2018-01-01'
            )
            )
            SELECT DATENAME(MONTH, d), COUNT(products2018.GTIN)
            FROM (VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11)) AS numbers(n)
            CROSS APPLY (SELECT DATEADD(MONTH, n, '2018-01-01')) AS dates(d)
            LEFT JOIN products2018 ON YEAR(products2018.Date) = YEAR(d) AND MONTH(products2018.Date) = MONTH(d)
            GROUP BY d
            ORDER BY d





            share|improve this answer























            • Hello Salman What about DATE = min(DATE)? I'm actually Getting more values in 2018 and that's wrong, it should be less.
              – MishMish
              Nov 23 '18 at 14:04










            • It seems to work for your posted data. Cannot tell where it is coming from but you can comment out the group by / count(*) to debug.
              – Salman A
              Nov 23 '18 at 14:07










            • I'm applying it to my live data which im working with, the difference is the WHERE Clause has just more sql in it. But the numbers are higher than expected, and yes it does work correctly with the above code, so can't tell what's wrong yet :(
              – MishMish
              Nov 23 '18 at 14:13










            • If my where clause has more sql, then it should be writen in both where clauses in your example right? here is an Image of how it looks like: prnt.sc/lm280r
              – MishMish
              Nov 23 '18 at 14:16










            • I think you can probably discard everything after 2018 in the not exists query (the only check is that the product did not exist before 2018). But I am not sure.
              – Salman A
              Nov 23 '18 at 14:20














            1












            1








            1






            You could simply use NOT EXISTS:



            WITH products2018 AS (
            SELECT *
            FROM @Products AS p
            WHERE Date >= '2018-01-01'
            AND NOT EXISTS (
            SELECT *
            FROM @Products AS x
            WHERE GTIN = p.GTIN
            AND Date < '2018-01-01'
            )
            )
            SELECT DATENAME(MONTH, d), COUNT(products2018.GTIN)
            FROM (VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11)) AS numbers(n)
            CROSS APPLY (SELECT DATEADD(MONTH, n, '2018-01-01')) AS dates(d)
            LEFT JOIN products2018 ON YEAR(products2018.Date) = YEAR(d) AND MONTH(products2018.Date) = MONTH(d)
            GROUP BY d
            ORDER BY d





            share|improve this answer














            You could simply use NOT EXISTS:



            WITH products2018 AS (
            SELECT *
            FROM @Products AS p
            WHERE Date >= '2018-01-01'
            AND NOT EXISTS (
            SELECT *
            FROM @Products AS x
            WHERE GTIN = p.GTIN
            AND Date < '2018-01-01'
            )
            )
            SELECT DATENAME(MONTH, d), COUNT(products2018.GTIN)
            FROM (VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11)) AS numbers(n)
            CROSS APPLY (SELECT DATEADD(MONTH, n, '2018-01-01')) AS dates(d)
            LEFT JOIN products2018 ON YEAR(products2018.Date) = YEAR(d) AND MONTH(products2018.Date) = MONTH(d)
            GROUP BY d
            ORDER BY d






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 23 '18 at 14:05

























            answered Nov 23 '18 at 13:53









            Salman A

            175k66336424




            175k66336424












            • Hello Salman What about DATE = min(DATE)? I'm actually Getting more values in 2018 and that's wrong, it should be less.
              – MishMish
              Nov 23 '18 at 14:04










            • It seems to work for your posted data. Cannot tell where it is coming from but you can comment out the group by / count(*) to debug.
              – Salman A
              Nov 23 '18 at 14:07










            • I'm applying it to my live data which im working with, the difference is the WHERE Clause has just more sql in it. But the numbers are higher than expected, and yes it does work correctly with the above code, so can't tell what's wrong yet :(
              – MishMish
              Nov 23 '18 at 14:13










            • If my where clause has more sql, then it should be writen in both where clauses in your example right? here is an Image of how it looks like: prnt.sc/lm280r
              – MishMish
              Nov 23 '18 at 14:16










            • I think you can probably discard everything after 2018 in the not exists query (the only check is that the product did not exist before 2018). But I am not sure.
              – Salman A
              Nov 23 '18 at 14:20


















            • Hello Salman What about DATE = min(DATE)? I'm actually Getting more values in 2018 and that's wrong, it should be less.
              – MishMish
              Nov 23 '18 at 14:04










            • It seems to work for your posted data. Cannot tell where it is coming from but you can comment out the group by / count(*) to debug.
              – Salman A
              Nov 23 '18 at 14:07










            • I'm applying it to my live data which im working with, the difference is the WHERE Clause has just more sql in it. But the numbers are higher than expected, and yes it does work correctly with the above code, so can't tell what's wrong yet :(
              – MishMish
              Nov 23 '18 at 14:13










            • If my where clause has more sql, then it should be writen in both where clauses in your example right? here is an Image of how it looks like: prnt.sc/lm280r
              – MishMish
              Nov 23 '18 at 14:16










            • I think you can probably discard everything after 2018 in the not exists query (the only check is that the product did not exist before 2018). But I am not sure.
              – Salman A
              Nov 23 '18 at 14:20
















            Hello Salman What about DATE = min(DATE)? I'm actually Getting more values in 2018 and that's wrong, it should be less.
            – MishMish
            Nov 23 '18 at 14:04




            Hello Salman What about DATE = min(DATE)? I'm actually Getting more values in 2018 and that's wrong, it should be less.
            – MishMish
            Nov 23 '18 at 14:04












            It seems to work for your posted data. Cannot tell where it is coming from but you can comment out the group by / count(*) to debug.
            – Salman A
            Nov 23 '18 at 14:07




            It seems to work for your posted data. Cannot tell where it is coming from but you can comment out the group by / count(*) to debug.
            – Salman A
            Nov 23 '18 at 14:07












            I'm applying it to my live data which im working with, the difference is the WHERE Clause has just more sql in it. But the numbers are higher than expected, and yes it does work correctly with the above code, so can't tell what's wrong yet :(
            – MishMish
            Nov 23 '18 at 14:13




            I'm applying it to my live data which im working with, the difference is the WHERE Clause has just more sql in it. But the numbers are higher than expected, and yes it does work correctly with the above code, so can't tell what's wrong yet :(
            – MishMish
            Nov 23 '18 at 14:13












            If my where clause has more sql, then it should be writen in both where clauses in your example right? here is an Image of how it looks like: prnt.sc/lm280r
            – MishMish
            Nov 23 '18 at 14:16




            If my where clause has more sql, then it should be writen in both where clauses in your example right? here is an Image of how it looks like: prnt.sc/lm280r
            – MishMish
            Nov 23 '18 at 14:16












            I think you can probably discard everything after 2018 in the not exists query (the only check is that the product did not exist before 2018). But I am not sure.
            – Salman A
            Nov 23 '18 at 14:20




            I think you can probably discard everything after 2018 in the not exists query (the only check is that the product did not exist before 2018). But I am not sure.
            – Salman A
            Nov 23 '18 at 14:20













            0














            This uses a Calendar Table instead, but perhaps this get's you what you are after?



            WITH CTE AS(
            SELECT CT.CalendarDate,
            CT.CalendarMonth,
            CT.CalendarMonthName,
            P.GTIN,
            P.[Location],
            P.[Date],
            MIN(P.[date]) OVER (PARTITION BY P.GTIN) AS MinDate
            FROM dbo.CalendarTable CT
            LEFT JOIN dbo.Products P ON CT.CalendarDate = P.[date]
            WHERE CT.CalendarYear IN (2017,2018))
            SELECT CTE.CalendarMonth,
            CTE.CalendarMonthName,
            COUNT(DISTINCT CASE WHEN CTE.MinDate > '20180101' THEN CTE.GTIN END) AS Products
            FROM CTE
            GROUP BY CTE.CalendarMonth,
            CTE.CalendarMonthName
            ORDER BY CTE.CalendarMonth;





            share|improve this answer


























              0














              This uses a Calendar Table instead, but perhaps this get's you what you are after?



              WITH CTE AS(
              SELECT CT.CalendarDate,
              CT.CalendarMonth,
              CT.CalendarMonthName,
              P.GTIN,
              P.[Location],
              P.[Date],
              MIN(P.[date]) OVER (PARTITION BY P.GTIN) AS MinDate
              FROM dbo.CalendarTable CT
              LEFT JOIN dbo.Products P ON CT.CalendarDate = P.[date]
              WHERE CT.CalendarYear IN (2017,2018))
              SELECT CTE.CalendarMonth,
              CTE.CalendarMonthName,
              COUNT(DISTINCT CASE WHEN CTE.MinDate > '20180101' THEN CTE.GTIN END) AS Products
              FROM CTE
              GROUP BY CTE.CalendarMonth,
              CTE.CalendarMonthName
              ORDER BY CTE.CalendarMonth;





              share|improve this answer
























                0












                0








                0






                This uses a Calendar Table instead, but perhaps this get's you what you are after?



                WITH CTE AS(
                SELECT CT.CalendarDate,
                CT.CalendarMonth,
                CT.CalendarMonthName,
                P.GTIN,
                P.[Location],
                P.[Date],
                MIN(P.[date]) OVER (PARTITION BY P.GTIN) AS MinDate
                FROM dbo.CalendarTable CT
                LEFT JOIN dbo.Products P ON CT.CalendarDate = P.[date]
                WHERE CT.CalendarYear IN (2017,2018))
                SELECT CTE.CalendarMonth,
                CTE.CalendarMonthName,
                COUNT(DISTINCT CASE WHEN CTE.MinDate > '20180101' THEN CTE.GTIN END) AS Products
                FROM CTE
                GROUP BY CTE.CalendarMonth,
                CTE.CalendarMonthName
                ORDER BY CTE.CalendarMonth;





                share|improve this answer












                This uses a Calendar Table instead, but perhaps this get's you what you are after?



                WITH CTE AS(
                SELECT CT.CalendarDate,
                CT.CalendarMonth,
                CT.CalendarMonthName,
                P.GTIN,
                P.[Location],
                P.[Date],
                MIN(P.[date]) OVER (PARTITION BY P.GTIN) AS MinDate
                FROM dbo.CalendarTable CT
                LEFT JOIN dbo.Products P ON CT.CalendarDate = P.[date]
                WHERE CT.CalendarYear IN (2017,2018))
                SELECT CTE.CalendarMonth,
                CTE.CalendarMonthName,
                COUNT(DISTINCT CASE WHEN CTE.MinDate > '20180101' THEN CTE.GTIN END) AS Products
                FROM CTE
                GROUP BY CTE.CalendarMonth,
                CTE.CalendarMonthName
                ORDER BY CTE.CalendarMonth;






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 23 '18 at 15:57









                Larnu

                15.5k41630




                15.5k41630






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447787%2fsql-server-retrieve-unique-rows-for-a-specific-year-but-not-if-they-are-created%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Contact image not getting when fetch all contact list from iPhone by CNContact

                    count number of partitions of a set with n elements into k subsets

                    A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks