Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
根据SQL中每月1日的字段值选择行_Sql_Sql Server - Fatal编程技术网

根据SQL中每月1日的字段值选择行

根据SQL中每月1日的字段值选择行,sql,sql-server,Sql,Sql Server,在下表中,我想选择一行,其中天=1,但该帐户应在月1日的天=0 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号,A有0天,B有30天,因此我只想要帐户A这段代码是针对ORACLE的

在下表中,我想选择一行,其中天=1,但该帐户应在月1日的天=0

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号,A有0天,B有30天,因此我只想要帐户A

这段代码是针对ORACLE的,但请看一看。这个想法是:

挑选* 来自帐户 其中天=1 和ACC在选定的帐户中 来自帐户 其中ACC_日期=TRUNC ACC_日期,“月”和天=0


尝试转换为MSSQL并运行。

使用窗口函数max with case尝试此操作,以确定是否有日期为1且日期为0的行,如果有,则使用该帐户当月的行号按日期递增的顺序返回第二行

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
你可以试试这个:

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

您使用哪种RDBMS?我使用MS SQL Server您尝试了什么?