0

我在数据库中有一个列类型。我想获取 A 类型的所有行和 B 类型的前 N ​​行,两者都按 DateCreated 排序。我可以编写一个查询来执行此操作吗?任何指针都会有所帮助。

4

3 回答 3

3
   SELECT *
     FROM tbl
    WHERE TYPE='A'
UNION ALL
   SELECT *
     FROM (
          SELECT TOP(N) *
            FROM tbl
           WHERE TYPE='B'
        ORDER BY DateCreated
      ) X
 ORDER BY DateCreated
于 2012-10-02T19:06:59.683 回答
2

假设这是来自具有以下结构或类似结构的一个表:

[type] [nchar](10) NULL,
[date] [smalldatetime] NULL,
[id] [int] IDENTITY(1,1) NOT NULL

(select * from [TableName] where [TableName].[type]='t1') 
union 
(select TOP 2* from [TableName]  where [TableName].[type]='t2') 
order by [date]desc

(用第二种类型的所需结果替换“TOP2”)

于 2012-10-02T19:07:59.967 回答
1

在 LINQ 中:

db
    .Where(x => x.Type == "A")
    .Union(db
        .Where(x => x.Type == "B")
        .OrderBy(x => x.SomeField)
        .Take(N));
    .OrderBy(x => x.DateCreated);
于 2012-10-03T12:52:02.487 回答