April 12, 2016 at 8:28 am
Hello,
I have a strange issue on querying a table to return Max datetime with a group by clause.
I am getting all dates as max instead of the actual maximum date. The date column has time elements too.
select emailaddress, max(DATEADD(dd, DATEDIFF(dd,0,ActivityDate), 0))
from tableA
where emailaddress = 'abctest@test.com'
group by emailaddress, DATEADD(dd, DATEDIFF(dd,0,ActivityDate), 0)
The data output comes like this:
abctest@test.com, 2014-08-14 00:00:00.000
abctest@test.com, 2012-11-28 00:00:00.000
abctest@test.com, 2013-09-24 00:00:00.000
abctest@test.com, 2014-09-01 00:00:00.000
I also tried DISTINCT clause with Select, but still not working.
Thank you,
Bij
April 12, 2016 at 8:34 am
datsun (4/12/2016)
Hello,I have a strange issue on querying a table to return Max datetime with a group by clause.
I am getting all dates as max instead of the actual maximum date. The date column has time elements too.
select emailaddress, max(DATEADD(dd, DATEDIFF(dd,0,ActivityDate), 0))
from tableA
where emailaddress = 'abctest@test.com'
group by emailaddress, DATEADD(dd, DATEDIFF(dd,0,ActivityDate), 0)
The data output comes like this:
abctest@test.com, 2014-02-18 00:00:00.000
abctest@test.com, 2014-08-14 00:00:00.000
abctest@test.com, 2012-11-28 00:00:00.000
abctest@test.com, 2013-09-24 00:00:00.000
abctest@test.com, 2014-09-01 00:00:00.000
I also tried DISTINCT clause with Select, but still not working.
Thank you,
Bij
Try taking the DATEADD calculation off the GROUP BY. Your query is grouping by that as well as the emailaddress.
CREATE TABLE ##myTable (emailaddress VARCHAR(20), activitydate datetime)
INSERT INTO ##myTable (emailaddress, activitydate) VALUES ('abctest@test.com','2014-02-18 00:00:00.000')
INSERT INTO ##myTable (emailaddress, activitydate) VALUES ('abctest@test.com','2014-08-14 00:00:00.000')
INSERT INTO ##myTable (emailaddress, activitydate) VALUES ('abctest@test.com','2012-11-28 00:00:00.000')
INSERT INTO ##myTable (emailaddress, activitydate) VALUES ('abctest@test.com','2013-09-24 00:00:00.000')
INSERT INTO ##myTable (emailaddress, activitydate) VALUES ('abctest@test.com','2014-09-01 00:00:00.000');
SELECT
emailaddress
,MAX(DATEADD(dd,DATEDIFF(dd,0,ActivityDate), 0))
FROM
##myTable
GROUP BY
emailaddress
DROP TABLE
##myTable
How to post a question to get the most help http://www.sqlservercentral.com/articles/Best+Practices/61537
April 12, 2016 at 9:37 am
BWFC,
yes that works. silly me forgot about the date column in group by clause. I had it as a column in the select clause initially, hence it stayed with the group by clause too.
many thanks,
Bij
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply