名称   类别    类型  产品链接
----  -----  ----  ----
A     cc     d1    h1
A     cc     d1    h2
A     cc     d2    h3
A     cc     d3    h4
A     cc     d2    h5
B     cc     d2    h6
B     cc     d2    h7
B     ee     d5    h8
B     ee     d5    h9
B     ff     d6    h10
B     gg     d8    h11对A和B的出现次数做统计,并把第一次出现的名称对应的类型和产品链接一并显示出来。
统计结果如下所示:
名称   次数    类型  产品链接
----  -----  ----  ----
A     5      d1    h1
B     6      d2    h6这样的查询语句该怎么写啊??

解决方案 »

  1.   


    with tb(a,b,c,d)as(
    select 'a','cc','d1','h1' union all
    select 'a','cc','d1','h2' union all
    select 'a','cc','d0','h0' union all
    select 'b','cc','d2','h6' union all
    select 'b','cc','d1','h1' union all
    select 'b','cc','d1','h7' 
    )
    select distinct a,(select COUNT(1) from tb where a=a.a),
    (select top 1 c from tb where a=a.a),(select top 1 d from tb where a=a.a) from tb a
    把列名改一下就行..
      

  2.   

    ----------------------------------------------------------------
    -- Author  :DBA_Huangzj(發糞塗牆)
    -- Date    :2013-05-08 16:02:13
    -- Version:
    --      Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64) 
    -- Jun 17 2011 00:54:03 
    -- Copyright (c) Microsoft Corporation
    -- Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
    --
    ----------------------------------------------------------------
    --> 测试数据:[huang]
    if object_id('[huang]') is not null drop table [huang]
    go 
    create table [huang]([名称] varchar(1),[类别] varchar(2),[类型] varchar(2),[产品链接] varchar(3))
    insert [huang]
    select 'A','cc','d1','h1' union all
    select 'A','cc','d1','h2' union all
    select 'A','cc','d2','h3' union all
    select 'A','cc','d3','h4' union all
    select 'A','cc','d2','h5' union all
    select 'B','cc','d2','h6' union all
    select 'B','cc','d2','h7' union all
    select 'B','ee','d5','h8' union all
    select 'B','ee','d5','h9' union all
    select 'B','ff','d6','h10' union all
    select 'B','gg','d8','h11'
    --------------开始查询--------------------------
    SELECT a.*,b.类型  ,b.产品链接 FROM(
    SELECT 名称 ,  COUNT(1)次数
    FROM huang 
    GROUP BY 名称) a INNER JOIN 
     (
    select * ,ROW_NUMBER()OVER(PARTITION BY 名称 ORDER BY GETDATE())id
    from [huang])b ON a.名称=b.名称 AND b.id=1----------------结果----------------------------
    /* 
    名称   次数          类型   产品链接
    ---- ----------- ---- ----
    A    5           d1   h1
    B    6           d2   h6
    */
      

  3.   

    SELECT [A]
          ,count(A)
          ,(select top(1) T1.C from [dbo].[test] T1 where T1.A=T2.A)
          ,(select top(1) T1.D from [dbo].[test] T1 where T1.A=T2.A)
      FROM [dbo].[test] as T2
      group by [A]
    GO