获取2种类型的行

时间:2012-10-02 18:47:15

标签: c# sql sql-server linq-to-sql

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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'替换为第二种类型所需的结果)

答案 2 :(得分: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);