表名:test_table(下面subject是AUTO_INCREMENT PRIMARY KEY)
subject(主题)    reply(回复)
1                  0
2                  0
3                  0
4                  0
5                  0
6                  0
7                  1            // 对subject为1的回复
8                  2            // 对subject为2的回复
9                  1            // 对subject为1的回复原来的sql语句:
SELECT * FROM test_table WHERE reply=0 ORDER BY subject DESC得到结果:
6                  0
5                  0
4                  0
3                  0
2                  0
1                  0现在希望根据回复来查询,如果reply对应的subject为比较新的,就显示在最前面,
希望得到下面结果:
1                  0
2                  0
6                  0
5                  0
4                  0
3                  0请问这个sql怎么写(表的结构不可能更改了),晚上结贴。谢谢

解决方案 »

  1.   

    有没有回复之后的时间字段?对时间进行排序
    SELECT * FROM test_table WHERE reply=0 ORDER BY 时间 DESC
      

  2.   


    SELECT a.* 
    FROM test_table a left join
        (select max(subject) subject,reply from test_table where reply <> 0 group by reply) b
        on a.subject = b.reply
    WHERE a.reply=0 
    ORDER BY isnull(b.subject,0),a.subject DESC
      

  3.   

    --得到结果:
    --6 0
    --5 0
    --4 0
    --3 0
    --2 0
    --1 0
    Create table test_table([subject] smallint,[reply] nvarchar(1))
    Insert into test_table
    Select 1,N'0'
    Union all Select 2,N'0'
    Union all Select 3,N'0'
    Union all Select 4,N'0'
    Union all Select 5,N'0'
    Union all Select 6,N'0'
    Union all Select 7,N'1'
    Union all Select 8,N'2'
    Union all Select 9,N'1'SELECT subject,reply
    FROM test_table AS a
    WHERE a.reply=0
    ORDER BY (SELECT COUNT(1) FROM test_table AS x WHERE x.reply=a.subject GROUP BY x.reply) DESC,a.subject DESC