日期:2014-05-17  浏览次数:20613 次

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
)
GO
INSERT INTO customer
SELECT '赵三',1 UNION
SELECT '钱三',1 UNION
SELECT '孙三',1 UNION
SELECT '李三',1 UNION
SELECT '周三',1 UNION
SELECT '吴三',1 UNION
SELECT '郑三',2 UNION
SELECT '王三',2 UNION
SELECT '赵三',2 UNION
SELECT '钱三',2 UNION
SELECT '孙三',2 


select customername,
       customertype
from customer t
where (select count(*) from customer where customertype=t.customertype and customername > t.customername )<3
ORDER 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 '李……