Home > Net >  Is there any query to only return 1 row for each product
Is there any query to only return 1 row for each product

Time:11-09

I want to make a query on my data and only want to return 1 row for each product name where date is bigger.

Data:

╔═══════════╦═════════════╦═══════╦═══════╗
║ ProductID ║ ProductName ║ Total ║ date  ║
╠═══════════╬═════════════╬═══════╬═══════╣
║      1001 ║ abc         ║    122    ║
║      1002 ║ abc         ║    234    ║
║      2002 ║ xyz         ║     85    ║
║      3004 ║ ytp         ║    151    ║
║      4001 ║ aze         ║    191    ║
╚═══════════╩═════════════╩═══════╩═══════╝

I mean I want to see this result:

╔═══════════╦═════════════╦═══════╦═══════╗
║ ProductID ║ ProductName ║ Total ║ date  ║
╠═══════════╬═════════════╬═══════╬═══════╣
║      1002 ║ abc         ║    234    ║
║      2002 ║ xyz         ║     85    ║
║      3004 ║ ytp         ║    151    ║
║      4001 ║ aze         ║    191    ║
╚═══════════╩═════════════╩═══════╩═══════╝

CodePudding user response:

Try this :

SELECT DISTINCT ON (ProductName)
       ProductID, ProductName, Total, date
  FROM your_table
 ORDER BY ProductName, date DESC

CodePudding user response:

SELECT *FROM
(
  SELECT X.ProductID,X.ProductName,X.Total,X.DATE,
    ROW_NUMBER()OVER(PARTITION BY X.PRODUCTNAME ORDER BY X.DATE DESC)XCOL
  FROM YOUR_TABLE AS X
)A WHERE A.XCOL=1

CodePudding user response:

Try this :

   SELECT a.ProductID, a.ProductName, a.Total, a.date
    FROM Product a
    INNER JOIN (
        SELECT ProductName, MAX(date) date
        FROM Product
        GROUP BY ProductName
    ) b ON a.ProductName = b.ProductName AND a.date = b.date
    order by a.ProductID

http://sqlfiddle.com/#!17/7ffd5/1

  • Related