1

このようなデータを含むテーブルがあります。

Id       PId         Device             Status          Type      Created_Date
===      ===         ======             ======          ====      ============
1         2           1                  today          High      2012-04-12 08:11:51.583
2         2           4                  today          Medium    2012-04-02 01:39:52.393
3         3           5                  today          Medium    2012-04-02 01:10:02.443
4         2           6                  today          High      2012-04-02 01:05:25.063
5         2           3                  today          High      2012-04-02 01:03:08.360
6         2           7                  today          High      2012-04-02 01:02:57.093
7         2           2                  today          High      2012-04-02 00:22:37.807

ここで、デバイス6と7のレコードを、作成日の降順で常にレコードセットの一番上に配置する必要があります。また、6と7を除くデバイスのレコードは、タイプと作成日で並べ替えられます。デバイスタイプ6と7のレコードの後に​​降順で表示されます。

したがって、望ましい結果は次のようになります。

Id       PId         Device             Status          Type      Created_Date
===      ===         ======             ======          ====      ============
4         2           6                  today          High      2012-04-02 01:05:25.063
6         2           7                  today          High      2012-04-02 01:02:57.093
1         2           1                  today          High      2012-04-12 08:11:51.583
5         2           3                  today          High      2012-04-02 01:03:08.360
7         2           2                  today          High      2012-04-02 00:22:37.807
2         2           4                  today          Medium    2012-04-02 01:39:52.393

私は以下のようにクエリを使用しました:

select * from TblAlert where PId=2 and ( Device=6 OR Device=7) and ( Status='Today' or Status=0)
UNION
Select * from TblAlert Where  PId=2 and ( Device<>6 OR Device<>7)and (Status='Today' or Status=0)
order by Type,Created_Date desc 

ただし、レコードセット全体にorder by句を適用しているため、機能しません。

誰かがこれに関して私を助けてくれますか?

4

2 に答える 2

4
select *
from TblAlert 
where PId=2 and ([Status]='Today' or [Status]='0')
order by case when Device in (6, 7) then 0 else 1 end,
         case when Device in (6, 7) then [Type] else '' end,
         Created_Date
于 2012-04-23T05:17:45.150 に答える
0

Table変数を次のように使用して自分で解決しました

DECLARE @Records TABLE
(
   Id  int,
   PId int,
   Device int,
   Status Alert_Type varchar(10),
   Type Alert_Type varchar(5), 
   Created_Date DateTime
); 

INSERT @Records 
    SELECT Id, PId, Device, Status,Type,Created_Date FROM 
        TblAlert 
    WHERE 
        PId =2
        AND Device IN (6,7) 
        AND ( Status='Today' or Status=0) 
    ORDER BY 
        Created_Date DESC; 

INSERT @Records 
    SELECT Id, PId, Device, Status,Type,Created_Date FROM 
        TblAlert 
    WHERE 
        PId =2
        AND Device NOT IN (6,7) 
        AND ( Status='Today' or Status=0) 
    ORDER BY 
        Type, Created_Date DESC; 

SELECT * FROM @Records;
于 2012-05-09T12:39:13.913 に答える