2017-02-24 58 views
-1

在下面的表我想选择一排,其中“天” = 1,但此帐户应当有天= 0在每月的1日。选择基于在每月的第一个字段值的行SQL

Account| Date | Days 
-------|------|----- 
A | 1/3/2015 | 0 
A | 5/3/2015 | 1 
A | 9/3/2015 | 10 
B | 1/3/2015 | 30 
B | 3/3/2015 | 1 
B | 6/3/2015 | 12 

结果应该是第二排

A  5/3/2015 1 

一日1为0天,但B有因此30天到想要只占一

+0

你使用哪种RDBMS? –

+0

我使用MS SQL服务器 – Sara

+0

你试过了什么? –

回答

0

此代码是ORACLE,而是采取看看。思想是:

SELECT * FROM ACCOUNTS WHERE DAYS = 1 和ACC IN(SELECT ACCOUNT FROM ACCOUNTS WHERE ACC_DATE = TRUNC(ACC_DATE, '月')和天数= 0)

尝试转换为MSSQL并运行。

0

试试这个使用窗函数maxcase以找出是否有与天= 1天= 0一排,如果有,增加日期才能在当月恢复使用row_number秒行该帐户。

select * 
from (
    select 
     t.*, 
     max(case when day(date) = 1 and Days = 0 then 1 end) 
      over (partition by Account, month(Date), year(Date)) flag, 
     row_number() over (
      partition by Account, month(Date), year(Date) 
      order by Date 
      ) rn 
    from your_table t 
) t where flag = 1 and rn = 2 
0

你可以试试这个:

SELECT account, date, days 
FROM table_name t 
WHERE days = 1 
    AND EXISTS (SELECT 1 
      FROM table_name 
      WHERE account = t.account 
       AND date = DATEADD(month, DATEDIFF(month, 0, t.date), 0) 
       --cast(date As Date) = DATEADD(month, DATEDIFF(month, 0, t.date), 0) 
       AND days = 0); 
相关问题