--我有一张表A
----------------------
-- id  ct   userid
--  1  aa    001
--  2  bb    001
--  3  cc    001
--  4  dd    002
--  5  ee    001
--使用select *from A where userid='001'得到如下结果:
----------------------
-- id  ct   userid
--  1  aa    001
--  2  bb    001
--  3  cc    001
--  5  ee    001
--但是我想得到这样的效果,意思就是在符合条件的记录中最前面加一个默认,这样能实现吗?sql语句该如何写:
--------------------
-- id  ct   userid
--  0  默认  001
--  1  aa    001
--  2  bb    001
--  3  cc    001
--  5  ee    001

解决方案 »

  1.   

    select id,'默认' as ct,userid from A where exists(select 1 from A where userid='001')
    union all
    select * from A where userid='001'
      

  2.   

    修正
    ---测试数据---
    if object_id('[A]') is not null drop table [A]
    go
    create table [A]([id] int,[ct] varchar(2),[userid] varchar(3))
    insert [A]
    select 1,'aa','001' union all
    select 2,'bb','001' union all
    select 3,'cc','001' union all
    select 4,'dd','002' union all
    select 5,'ee','001'
     
    ---查询---
    select DISTINCT 0 as id,'默认' as ct,userid from A where userid='001'
    union all
    select * from A where userid='001'---结果---
    id          ct   userid
    ----------- ---- ------
    0           默认   001
    1           aa   001
    2           bb   001
    3           cc   001
    5           ee   001(5 行受影响)
      

  3.   

    select id,ct = case WHEN id =(select top 1 id from A where userid =1 order by id asc) THEN '默认'  ELSE ct END,userid from A where userid =1 order by id asc
      

  4.   

    多谢josy大哥,这就是我想要的结果。