I have this sample where I am counting the number of records and displaying them as CustomerIDCount
. I would also like to include the LatestDate
but I am not sure if I need another query or I can add it to this one?
Setup
CREATE TABLE log
(
[CustomerID] [int] NULL,
[LogDate] [datetime] NULL
);
INSERT INTO log ([CustomerID], [LogDate])
VALUES
(1, 2021-02-12),
(2, 2021-02-12),
(1, 2021-02-12),
(3, 2021-03-12),
(4, 2021-02-12)
;
My attempt:
SELECT
CustomerID, COUNT(*) CustomerIDCount
FROM
(SELECT CustomerID
FROM log) g
GROUP BY
CustomerID
ORDER BY
CustomerIDCount
Results:
CustomerID | CustomerIDCount |
---|---|
2 | 1 |
3 | 1 |
4 | 1 |
1 | 2 |
But my desired results would be:
CustomerID | CustomerIDCount | LatestDate |
---|---|---|
2 | 1 | 2021-02-12 |
3 | 1 | 2021-03-12 |
4 | 1 | 2021-02-12 |
1 | 2 | 2021-03-12 |
Hard to tell from this limited information, and am assuming you have a Group By on customer ID, with a COUNT. Can you just add MAX(LatestDate) to that query?
SELECT CustomerID , Count(*) AS CustomerIDCount , Max(LogDate) AS LastestDate FROM log GROUP BY CustomerID ;
You don't need to use a sub-query, and you can just add Max(LogDate) to the query.
select CustomerID, count(*) CustomerIDCount, max(LogDate) as max_LogDate
from log
group by CustomerID
order by CustomerIDCount
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.