22,300
社区成员




----------------------------------------------------------------
-- 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
*/
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
把列名改一下就行..