Suppose I've table
table :: tbl_group_txn
GroupName Indvd_id effective_date amount
--------------------------------------------------------------
JPN001 001 2015-11-13 00:00:00.000 70,000
JPN001 002 2015-11-13 00:00:00.000 80,000
JPN001 003 2015-11-16 00:00:00.000 90,000
JPN001 004 2015-11-16 00:00:00.000 75,000
JPN001 005 2015-11-29 00:00:00.000 100,000
JPN001 006 2015-11-29 00:00:00.000 125,000
CHN001 007 2015-11-29 00:00:00.000 60,000
CHN001 008 2015-11-15 00:00:00.000 70,000
CHN001 009 2015-11-15 00:00:00.000 70,000
CHN001 010 2015-11-18 00:00:00.000 40,000
--------------------------------------------------------------
My requirement is to get the rows under the same group with MAX(effective_date )rows for the date till today date and all the rows greater than today date .
In case of group JPN001 , the rowid 3, 4 has max date till today date and rowid 5, 6 are rows having date greater than today date.
Similary in case of group CHN001 , the rowid 10 has max date till today date and rowid 7 have date greater than today rate.
So the output will be ::
GroupName Indvd_id effective_date amount
--------------------------------------------------------------
JPN001 003 2015-11-16 00:00:00.000 90,000
JPN001 004 2015-11-16 00:00:00.000 75,000
JPN001 005 2015-11-29 00:00:00.000 100,000
JPN001 006 2015-11-29 00:00:00.000 125,000
CHN001 007 2015-11-29 00:00:00.000 60,000
CHN001 010 2015-11-18 00:00:00.000 40,000
--------------------------------------------------------------
Please suggest how can I achieve this?
In the first part of query, I get all rows with effective_date equal to MAX effective_date until today (with a fixed groupname) and with OR condition, I get all rows with effective_date > today date
Try this:
SELECT T.*
FROM mytable T
WHERE T.effective_date =
(SELECT MAX(T2.effective_date)
FROM mytable T2
WHERE T2.groupname = T.groupname
AND T2.effective_date <= GETDATE())
OR T.effective_date > GETDATE()
Go on SqlFiddle
In this select query i used DATEADD function in where clause to get all rows with max(effective_date)>today_date
Try this:
select *,effective_date
from #tbl_group_txn
where effective_date>=dateadd(dd,datediff(dd,0,getdate()),-2)
group by GroupName,Indvd_id,effective_date,amount
order by Indvd_id
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.