2017-02-24 54 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); 
相關問題