【问题标题】:select rows with max date till current date as well as all the rows greater than today date选择最大日期到当前日期的行以及大于今天日期的所有行
【发布时间】:2015-11-18 09:42:43
【问题描述】:

假设我有桌子

表 :: 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
--------------------------------------------------------------

我的要求是使用 MAX(effective_date )rows 获取同一组下的行,直到今天的日期和 所有大于今天日期的行

在组 JPN001 的情况下,rowid 3、4 的最大日期为今天日期,rowid 5、6 是日期大于今天日期的行。

在组 CHN001 的情况下类似,rowid 10 的最大日期是到今天的日期,而 rowid 7 的日期大于今天的汇率。

所以输出将是::

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
--------------------------------------------------------------

请建议我怎样才能做到这一点?

【问题讨论】:

    标签: sql sql-server date


    【解决方案1】:

    在查询的第一部分,我得到所有有效日期等于 MAX 有效日期的行,直到今天(具有固定组名)和 OR 条件,我得到所有有效日期>今天日期的行

    试试这个:

    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()
    

    继续SqlFiddle

    【讨论】:

      【解决方案2】:
        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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多