Reputation: 597
I need to group only by one column
SQL Server 2012 query:
SELECT OrderID,Status,DateEdited
FROM orders
WHERE Status='Pending'
GROUP BY OrderID,Status,DateEdited
and the result is:
As you can see there are duplicate OrderId
column values.
Works but it groups by OrderId,Status,DateEdit
but what I need is that the OrderId
would be unique in the results can I have something like:
SELECT OrderID,Status,DateEdited
FROM orders
WHERE Status='Pending'
GROUP BY OrderID
Upvotes: 0
Views: 4866
Reputation: 79949
You have to use an aggregate function for status
and DateEdited
, to get distinct valeus for each grouped ORDERID
. You can also use the ranking functions to do so like this:
WITH CTE
AS
(
SELECT
OrderID,
Status,
DateEdited,
ROW_NUMBER() OVER(PARTITION BY OrderID ORDER BY DateEdited DESC) rownum
FROM orders
WHERE Status='Pending'
)
SELECT
OrderID,
Status,
DateEdited
FROM CTE
WHERE rownum = 1;
This will give you distinct ORDERID
s. But which status and DateEdited
to return for each grouped ORDERID
?
Upvotes: 4
Reputation: 10063
Then you can do like this,
SELECT OrderID,'Pending' as Status,max(DateEdited)
FROM orders
WHERE Status='Pending'
GROUP BY OrderID
If you dont want to loose any record then you can go for GROUP_CONCAT()
SELECT OrderID,'Pending' as Status,GROUP_CONCAT(DateEdited)
FROM orders
WHERE Status='Pending'
GROUP BY OrderID
Note: Am not sure whether you GROUP_CONCAT in sqlserver Incase it's not there go for a function like that. :)
Upvotes: 1