SQL Query Multiple Columns Using Distinct on One Column Only

后端 未结 6 745
余生分开走
余生分开走 2020-12-05 18:04

I am trying to write a SQL query that selects multiple columns from a table with the distinct operator on one column only.

The table is simple. The columns are:

6条回答
  •  爱一瞬间的悲伤
    2020-12-05 18:59

    you have various ways to distinct values on one column or multi columns.

    • using the GROUP BY

      SELECT DISTINCT MIN(o.tblFruit_ID)  AS tblFruit_ID,
         o.tblFruit_FruitType,
         MAX(o.tblFruit_FruitName)
      FROM   tblFruit  AS o
      GROUP BY
           tblFruit_FruitType
      
    • using the subquery

      SELECT b.tblFruit_ID,
         b.tblFruit_FruitType,
         b.tblFruit_FruitName
      FROM   (
             SELECT DISTINCT(tblFruit_FruitType),
                    MIN(tblFruit_ID) tblFruit_ID
             FROM   tblFruit
             GROUP BY
                    tblFruit_FruitType
         ) AS a
         INNER JOIN tblFruit b
              ON  a.tblFruit_ID = b.tblFruit_I
      
    • using the join with subquery

      SELECT t1.tblFruit_ID,
          t1.tblFruit_FruitType,
          t1.tblFruit_FruitName
      FROM   tblFruit  AS t1
         INNER JOIN (
                  SELECT DISTINCT MAX(tblFruit_ID) AS tblFruit_ID,
                         tblFruit_FruitType
                  FROM   tblFruit
                  GROUP BY
                         tblFruit_FruitType
              )  AS t2
              ON  t1.tblFruit_ID = t2.tblFruit_ID 
      
    • using the window functions only one column distinct

      SELECT tblFruit_ID,
          tblFruit_FruitType,
          tblFruit_FruitName
      FROM   (
               SELECT tblFruit_ID,
                    tblFruit_FruitType,
                    tblFruit_FruitName,
                    ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_ID) 
          rn
             FROM   tblFruit
          ) t
          WHERE  rn = 1 
      
    • using the window functions multi column distinct

      SELECT tblFruit_ID,
          tblFruit_FruitType,
          tblFruit_FruitName
      FROM   (
               SELECT tblFruit_ID,
                    tblFruit_FruitType,
                    tblFruit_FruitName,
                    ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType,     tblFruit_FruitName 
          ORDER BY tblFruit_ID) rn
                FROM   tblFruit
           ) t
          WHERE  rn = 1 
      

提交回复
热议问题