同一查询中的多个Counts()

时间:2017-01-19 18:04:13

标签: sql sql-server

我有一个现有的查询,它返回一个如下所示的结果集:

ID    ContactID     ContactName    Amount
-------------------------------------------
1        42           Joe          $5.00
2        42           Joe          $6.00
3        96           Tim          $1.00
4        96           Tim          $3.00
5        96           Tim          $9.00

现在,在每行中,我需要通过ContactID进行计数

ID        Count    ContactID     ContactName    Amount
--------------------------------------------------------
1          2        42           Joe          $5.00
2          2        42           Joe          $6.00
3          3        96           Tim          $1.00
4          3        96           Tim          $3.00
5          3        96           Tim          $9.00

这是当前的查询:

SELECT 
    ls.LeadSalesID, 
    ls.SoldToContactID,
    c.FirstName, 
    ls.Amount
FROM 
    LeadSales ls
    JOIN Contacts c ON c.ContactID = ls.SoldToContactID
WHERE
    ls.LeadSalesCreditStatus = 1

我已尝试GROUPING所有SELECT中的所有列,然后添加COUNT(ls.SoldToContactID),但COUNT列返回所有1。

谢谢!

1 个答案:

答案 0 :(得分:3)

使用count窗口功能。

SELECT 
    ls.LeadSalesID, 
    ls.SoldToContactID,
    c.FirstName, 
    ls.Amount,
    COUNT(*) OVER(PARTITION BY c.ContactID) as cnt
FROM 
    LeadSales ls
    JOIN Contacts c ON c.ContactID = ls.SoldToContactID
WHERE
    ls.LeadSalesCreditStatus = 1