Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Database & SysAdmin
  3. Database
  4. Select records using distinct and order by [modified]

Select records using distinct and order by [modified]

Scheduled Pinned Locked Moved Database
databasequestion
8 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Offline
    P Offline
    popchecker
    wrote on last edited by
    #1

    I am using MS Sql 2005. In my database I have a table "Products" which has following structure and content

    ProductName CategoryId AddedDate

    Product1 1 04/12/2010
    Product2 1 04/12/2010
    Product3 2 05/12/2010
    Product4 1 06/12/2010

    I want to fetch top 2 records order by AddedDate. To do that I can use sql

    Select top 2 * From Products Order By AddedDate

    This will populate first two records. Both are in CategoryId "1". I want to Select records from distinct categories. I requirment is to select records order by AddedDate with distinct CategoryId. I can do it with temporary tables. But is there any simple query to do that? Thanks and regards, Poppy

    modified on Thursday, May 27, 2010 9:33 AM

    B L 2 Replies Last reply
    0
    • P popchecker

      I am using MS Sql 2005. In my database I have a table "Products" which has following structure and content

      ProductName CategoryId AddedDate

      Product1 1 04/12/2010
      Product2 1 04/12/2010
      Product3 2 05/12/2010
      Product4 1 06/12/2010

      I want to fetch top 2 records order by AddedDate. To do that I can use sql

      Select top 2 * From Products Order By AddedDate

      This will populate first two records. Both are in CategoryId "1". I want to Select records from distinct categories. I requirment is to select records order by AddedDate with distinct CategoryId. I can do it with temporary tables. But is there any simple query to do that? Thanks and regards, Poppy

      modified on Thursday, May 27, 2010 9:33 AM

      B Offline
      B Offline
      Blue_Boy
      wrote on last edited by
      #2

      SELECT DISTINCT TOP 2 p.CategoryId, (SELECT TOP 1 p2.AddDate FROM products p2 WHERE p2.CategoryId = p. CategoryId) AS adddate FROM products p ORDER BY p.CategoryId Hope this will help you.


      I Love T-SQL "Don't torture yourself,let the life to do it for you." If my post helps you kindly save my time by voting my post. www.aktualiteti.com

      modified on Thursday, May 27, 2010 10:45 AM

      P 1 Reply Last reply
      0
      • B Blue_Boy

        SELECT DISTINCT TOP 2 p.CategoryId, (SELECT TOP 1 p2.AddDate FROM products p2 WHERE p2.CategoryId = p. CategoryId) AS adddate FROM products p ORDER BY p.CategoryId Hope this will help you.


        I Love T-SQL "Don't torture yourself,let the life to do it for you." If my post helps you kindly save my time by voting my post. www.aktualiteti.com

        modified on Thursday, May 27, 2010 10:45 AM

        P Offline
        P Offline
        popchecker
        wrote on last edited by
        #3

        Please correct me if I am wrong. This will sort the results order by CategoryId not by AddedDate. But I could learn something from your SQL. Thanks for your help. Regards, Poppy

        1 Reply Last reply
        0
        • P popchecker

          I am using MS Sql 2005. In my database I have a table "Products" which has following structure and content

          ProductName CategoryId AddedDate

          Product1 1 04/12/2010
          Product2 1 04/12/2010
          Product3 2 05/12/2010
          Product4 1 06/12/2010

          I want to fetch top 2 records order by AddedDate. To do that I can use sql

          Select top 2 * From Products Order By AddedDate

          This will populate first two records. Both are in CategoryId "1". I want to Select records from distinct categories. I requirment is to select records order by AddedDate with distinct CategoryId. I can do it with temporary tables. But is there any simple query to do that? Thanks and regards, Poppy

          modified on Thursday, May 27, 2010 9:33 AM

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #4

          Let's start out with a basic testscript that other posters can abuse to test on their machines;

          DECLARE @Product TABLE (
          [Name] NVARCHAR(250)
          ,[refCategory] BIGINT
          ,[Added] DATETIME DEFAULT GETDATE()

          PRIMARY KEY ([Name])
          )

          INSERT INTO @Product
          -- Name Category Added
          SELECT 'Product1', 1, '20101204' UNION
          SELECT 'Product2', 1, '20101206' UNION
          SELECT 'Product3', 2, '20101205' UNION
          SELECT 'Product4', 1, '20101204' UNION
          SELECT 'Product5', 1, '20101209' UNION
          SELECT 'Product6', 2, '20101206' UNION
          SELECT 'Product7', 2, '20101204' UNION
          SELECT 'Service1', 3, '20100101'

          The testset is somewhat larger to make it somewhat easier to interpret what I'm looking at.

          popchecker wrote:

          I want to Select records from distinct categories. I requirment is to select records order by AddedDate with distinct CategoryId.

          If I understand correctly, then you want to group the data by category, sort within that group on the date, and take the top 2 records from each group? Sql Server 2005 supports "Common Table Expressions", which you could use as an alternative to a temporary table, like this;

          SELECT [Name], [refCategory], [Added]
          FROM(
          SELECT [refCategory],
          [Added],
          [Name],
          row_number() OVER (
          PARTITION BY [refCategory]
          ORDER BY [Added] ASC
          ) AS [catGroup]
          FROM @Product
          GROUP BY [refCategory], [Added], [Name]
          ) AS ProductCTE
          WHERE [catGroup] <= 2
          ORDER BY [refCategory] ASC, [Added] ASC

          I are Troll :suss:

          I 1 Reply Last reply
          0
          • L Lost User

            Let's start out with a basic testscript that other posters can abuse to test on their machines;

            DECLARE @Product TABLE (
            [Name] NVARCHAR(250)
            ,[refCategory] BIGINT
            ,[Added] DATETIME DEFAULT GETDATE()

            PRIMARY KEY ([Name])
            )

            INSERT INTO @Product
            -- Name Category Added
            SELECT 'Product1', 1, '20101204' UNION
            SELECT 'Product2', 1, '20101206' UNION
            SELECT 'Product3', 2, '20101205' UNION
            SELECT 'Product4', 1, '20101204' UNION
            SELECT 'Product5', 1, '20101209' UNION
            SELECT 'Product6', 2, '20101206' UNION
            SELECT 'Product7', 2, '20101204' UNION
            SELECT 'Service1', 3, '20100101'

            The testset is somewhat larger to make it somewhat easier to interpret what I'm looking at.

            popchecker wrote:

            I want to Select records from distinct categories. I requirment is to select records order by AddedDate with distinct CategoryId.

            If I understand correctly, then you want to group the data by category, sort within that group on the date, and take the top 2 records from each group? Sql Server 2005 supports "Common Table Expressions", which you could use as an alternative to a temporary table, like this;

            SELECT [Name], [refCategory], [Added]
            FROM(
            SELECT [refCategory],
            [Added],
            [Name],
            row_number() OVER (
            PARTITION BY [refCategory]
            ORDER BY [Added] ASC
            ) AS [catGroup]
            FROM @Product
            GROUP BY [refCategory], [Added], [Name]
            ) AS ProductCTE
            WHERE [catGroup] <= 2
            ORDER BY [refCategory] ASC, [Added] ASC

            I are Troll :suss:

            I Offline
            I Offline
            i j russell
            wrote on last edited by
            #5

            Thanks for the test script.

            SELECT p.refCategory, t.Name, t.Added
            FROM
            (SELECT DISTINCT refCategory
            FROM @Product) p
            CROSS APPLY
            (SELECT TOP 1 Name, Added
            FROM @Product
            WHERE refCategory = p.refCategory
            ORDER BY Added ASC) t

            T M L 3 Replies Last reply
            0
            • I i j russell

              Thanks for the test script.

              SELECT p.refCategory, t.Name, t.Added
              FROM
              (SELECT DISTINCT refCategory
              FROM @Product) p
              CROSS APPLY
              (SELECT TOP 1 Name, Added
              FROM @Product
              WHERE refCategory = p.refCategory
              ORDER BY Added ASC) t

              T Offline
              T Offline
              Tripathi Swati
              wrote on last edited by
              #6

              Hi russell , 5 from my side. This will run perfectly...

              Reasons are not Important but Results are Important. http://www.sql4professional.blogspot.com Swati Tripathi

              modified on Friday, May 28, 2010 1:46 AM

              1 Reply Last reply
              0
              • I i j russell

                Thanks for the test script.

                SELECT p.refCategory, t.Name, t.Added
                FROM
                (SELECT DISTINCT refCategory
                FROM @Product) p
                CROSS APPLY
                (SELECT TOP 1 Name, Added
                FROM @Product
                WHERE refCategory = p.refCategory
                ORDER BY Added ASC) t

                M Offline
                M Offline
                Mycroft Holmes
                wrote on last edited by
                #7

                Learn something every day, I'd have gone with the rownumber/partition solution. I've never used cross apply!

                Never underestimate the power of human stupidity RAH

                1 Reply Last reply
                0
                • I i j russell

                  Thanks for the test script.

                  SELECT p.refCategory, t.Name, t.Added
                  FROM
                  (SELECT DISTINCT refCategory
                  FROM @Product) p
                  CROSS APPLY
                  (SELECT TOP 1 Name, Added
                  FROM @Product
                  WHERE refCategory = p.refCategory
                  ORDER BY Added ASC) t

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #8

                  Cool! Thanks for updating it :)

                  I are Troll :suss:

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups