SQL计数在多行中

时间:2015-10-28 11:55:36

标签: sql

我有这个问题:

Select 
    ID, Date, Partner
From 
    Orders
Order By 
    Data Desc

结果:

ID  Date  Partner
1   27    x
2   16    y
3   06    z
4   04    x
5   02    z

如何使用count(Partner)获取此结果:

ID  Date  Partner  Count
1   27    x        2
2   16    y        1 
3   06    z        2
4   04    x        2
5   02    z        2

4 个答案:

答案 0 :(得分:2)

对于MS SQL,您可以使用Window function COUNT:

Select 
ID, Date, Partner,
count (*) OVER (PARTITION BY Partner) 
from Orders
ORDER BY Date Desc

答案 1 :(得分:1)

在大多数数据库中,您可以使用ANSI标准窗口功能:

select o.id, o.date, o.partner,
       count(*) over (partition by partner) as cnt
from orders o;

答案 2 :(得分:0)

使用相关的子查询进行计数:

Select 
ID, Date, Partner, (select count(*) from Orders o2
                    where o1.Partner = o2.Partner)
from Orders o1
ORDER BY Data Desc

答案 3 :(得分:0)

Select 
ID, Data, Z.Partner,Cnt
from Orders O
inner join
(select Partner, count(Partner) as cnt
from Orders
group by Partner)Z
on O.Partner = Z.Partner
order by Data desc