vchar_name
-----------
白菜
-----------
胡萝卜
-----------
白菜
------------
黄瓜
-----------
胡萝卜
-----------
胡萝卜
-----------想求拥有最小数据量的那种蔬菜名称
最终结果为:黄瓜。这样的sql语句应该如何写?
标题党了,sorry!

解决方案 »

  1.   

    select vchar_name from tb group by vchar_name having count(1)=1
      

  2.   

    select top 1 vchar_name from tb group by vchar_name order by count(1)
      

  3.   

    create table tb(vchar_name varchar(20))
    insert into tb values('白菜')
    insert into tb values('胡萝卜')
    insert into tb values('白菜')
    insert into tb values('黄瓜')
    insert into tb values('胡萝卜')
    insert into tb values('胡萝卜')
    goselect top 1 vchar_name from tb group by vchar_name order by count(1)drop table tb/*
    vchar_name           
    -------------------- 
    黄瓜(所影响的行数为 1 行)*/
      

  4.   

    --> 测试数据:#tb
    if object_id('tempdb.dbo.#tb') is not null drop table #tb
    go
    create table #tb([vchar_name] varchar(6))
    insert #tb
    select '白菜' union all
    select '胡萝卜' union all
    select '白菜' union all
    select '黄瓜' union all
    select '胡萝卜' union all
    select '胡萝卜'--------------------------------查询开始------------------------------select vchar_name from #tb group by vchar_name having count(1)=1
    /*
    vchar_name
    ----------
    黄瓜(1 行受影响)
    */
      

  5.   

    create table tb(vchar_name varchar(20))
    insert into tb values('白菜')
    insert into tb values('胡萝卜')
    insert into tb values('白菜')
    insert into tb values('黄瓜')
    insert into tb values('胡萝卜')
    insert into tb values('胡萝卜')
    go--如果你最小的数据只有一个,则如下:
    select top 1 vchar_name from tb group by vchar_name order by count(1)
    /*
    vchar_name           
    -------------------- 
    黄瓜(所影响的行数为 1 行)
    */--如果你最小的数据不止一个,例如添加一个测试数据
    insert into tb values('青菜')select vchar_name from tb group by vchar_name having count(1) = (select min(cnt) from
    (select vchar_name , count(1) cnt from tb group by vchar_name) t)
    /*
    vchar_name           
    -------------------- 
    黄瓜
    青菜(所影响的行数为 2 行)
    */drop table tb
      

  6.   

    DECLARE @TB table(vchar_name nvarchar(20))
    insert @TB
    select '白菜' union all
    select '胡萝卜' union all
    select '白菜' union all
    select '黄瓜' union all
    select '胡萝卜' union all
    select '胡萝卜'
    SELECT TOP(1) vchar_name
    FROM @TB
    GROUP BY vchar_name
    ORDER BY count(1)vchar_name
    --------------------
    黄瓜
      

  7.   

    select top 1 vchar_name from tb group by vchar_name order by count(1)