当前位置: 代码迷 >> Sql Server >> MSSQL查询 每类别型取若干条数据
  详细解决方案

MSSQL查询 每类别型取若干条数据

热度:79   发布时间:2016-04-27 11:23:33.0
MSSQL查询 每种类型取若干条数据
假设现在有customer表,这个表只有两个字段,客户姓名和客户类型,要求用一条语句每种客户类型取5条数据出来,这个语句怎么写,求助,谢谢

------解决方案--------------------
SQL code
--05以上可以用partition by然后取前5
------解决方案--------------------
SQL code
with customer as(    客户姓名,    客户类型,    row_number() over(partition by 客户类型 order by getdate()) as V_rank)select * from customer where v_rank<=5
------解决方案--------------------
SQL code
;with aaa as(    select row_number() over(partition by [客户类型] order by newid()) as rowindex,*    from customer)select * from aaa where rowindex<6
------解决方案--------------------
SQL code
CREATE TABLE customer(    customername VARCHAR(100),    customertype INT)GOINSERT INTO customerSELECT '赵三',1 UNIONSELECT '钱三',1 UNIONSELECT '孙三',1 UNIONSELECT '李三',1 UNIONSELECT '周三',1 UNIONSELECT '吴三',1 UNIONSELECT '郑三',2 UNIONSELECT '王三',2 UNIONSELECT '赵三',2 UNIONSELECT '钱三',2 UNIONSELECT '孙三',2 select customername,       customertypefrom customer twhere (select count(*) from customer where customertype=t.customertype and customername > t.customername )<3ORDER BY customertype
------解决方案--------------------
探讨
SQL code


CREATE TABLE customer
(
customername VARCHAR(100),
customertype INT
)
GO
INSERT INTO customer
SELECT '赵三',1 UNION
SELECT '钱三',1 UNION
SELECT '孙三',1 UNION
SELECT '李三',1 ……

------解决方案--------------------
探讨
引用:
SQL code


CREATE TABLE customer
(
customername VARCHAR(100),
customertype INT
)
GO
INSERT INTO customer
SELECT '赵三',1 UNION
SELECT '钱三',1 UNION
SELECT '孙三',1 UNION
SELECT '李……
  相关解决方案