日期:2014-05-18 浏览次数:20532 次
-->生成测试数据: GO IF OBJECT_ID('TBL')IS NOT NULL DROP TABLE TBL GO CREATE TABLE TBL( 日期 DATE, 备注 VARCHAR(100) ) GO INSERT TBL SELECT '2012-03-02','B' UNION ALL SELECT '2012-03-05','C' UNION ALL SELECT '2012-03-06','D' UNION ALL SELECT '2012-03-07','E' UNION ALL SELECT '2012-03-09','F' UNION ALL SELECT '2012-03-11','G' UNION ALL SELECT '2012-03-12','H' UNION ALL SELECT '2012-03-13','I' UNION ALL SELECT '2012-03-15','J' UNION ALL SELECT '2012-03-19','K' UNION ALL SELECT '2012-03-20','L' --不使用union all ;with t as( select *,case when 日期>=getdate() then 1 else 0 end as A from tbl ) select 日期,备注 from t order by a,(case when a=1 then 日期 end), (case when a=0 then 日期 end) desc /* 日期 备注 2012-03-09 F 2012-03-07 E 2012-03-06 D 2012-03-05 C 2012-03-02 B 2012-03-11 G 2012-03-12 H 2012-03-13 I 2012-03-15 J 2012-03-19 K 2012-03-20 L */ 估计得用case when 了,这个你看看
------解决方案--------------------
SELECT B.AA_ID,B.BB_ID FROM CC B,( SELECT BB_ID,MIN(AA.CreateDate) AS DT FROM CC,AA WHERE AA.AA_ID =CC.AA_ID GROUP BY CC.BB_ID ) AS T WHERE B.BB_ID=T.BB_ID ORDER BY T.DT,B.BB_ID
------解决方案--------------------
aa1 bb1
aa1 bb2
aa3 bb3
aa3 bb3
aa2 bb4
结果是
aa1 bb1
aa1 bb5
aa2 bb3
aa4 bb3
aa3 bb4
是这样的需求吗
------解决方案--------------------
好像比较简单: select * from cc c left join aa a on a.aa_id=c.aa_id left join bb b on b.bb_id=c.bb_id order by a.createdate,b.bb_id