是否可以为以下场景编写单个查询?

时间:2011-12-01 05:33:35

标签: sql-server

是否可以为以下场景编写单个查询?

情景 -

表 -

column name      -          id           date                isPaid
values           -           1        1/1/2011                1
                             2        1/2/2011                1
                             3        1/3/2011                0
                             4        1/4/2011                0
                             5        1/5/2011                0

我想要一个包含(所有ispaid = 1)和(只有1行ispaid = 0,其日期较小)的结果集。

结果集:

column name         -       id           date                isPaid
values              -        1        1/1/2011                1
                             2        1/2/2011                1
                             3        1/3/2011                0

由于

3 个答案:

答案 0 :(得分:2)

您可以使用UNIONdocs

SELECT
    [id],
    [date],
    [isPaid]
FROM
    [tablename]
WHERE 
    [ispaid] = 1

UNION ALL

SELECT TOP 1
    [id],
    [date],
    [isPaid]
FROM
    [tablename]
WHERE 
    [ispaid] = 0
ORDER BY 
    [date] ASC

答案 1 :(得分:1)

这应该可以满足SQL Server 2005及更高版本的需要。

select
   [id],
   [date],
   isPaid
from (  
     select 
         [id],
         [date],
         isPaid,
         ROW_NUMBER() over (partition by ispaid order by date) as row
     from table_name t ) a
where ispaid = 1
    or row = 1
order by [date]

答案 2 :(得分:0)

假设用户将向查询提供日期,以便检索数据

select t.* 
from table t,
(select Top 1 id, date, ispaid
from table
where ispaid = 0 and date<?) np
where (t.ispaid=1 and t.date = ? ) OR (t.id = np.id)