1

在以下示例SQL Fiddle

我应该如何继续获取每个“电话”的累积价格而不是获取最后一个值?

在下面给出的示例中,我需要生成下表:

Phone   Price   Purchases
50       35         3
51       50         2
52       99         3
55       21         2
53       16         2
54       21         1
56       16         1
58       22         1
57       10         2

这将在 SQL-Server 2012 中完成

提前致谢。

4

3 回答 3

2

您应该能够使用以下内容:

select c1.phone,
  c2.TotalPrice,
  c1.purchases
from supportContacts c1
inner join
(
  select 
    max(Fecha) maxFecha,
    sum(price) TotalPrice, 
    phone
  from supportContacts
  group by phone
) c2
  on c1.phone = c2.phone
  and c1.Fecha  = c2.maxFecha
order by c1.phone;

请参阅SQL Fiddle with Demo

子查询获取每个电话的总和以及与电话关联的最大 fecha。phone然后,您使用它并在 the和 the上加入您的表fecha以获得结果。

于 2013-04-11T16:38:16.343 回答
0

我手边没有 SQL Server 2012,但试一试:

  select     
    phone,     
    purchases,
    price, 
    sum(price) over (partition by phone order by phone, price) as running_sum_purchases
 FROM 
    supportContacts
于 2013-04-11T16:27:40.793 回答
0

不就是...

SELECT Phone, Sum(Price), Count(Purchases)
FROM  supportContacts
GROUP BY Phone
ORDER BY 1

..还是我错过了什么? http://sqlfiddle.com/#!6/7b36f/41

50 35 3
51 50 4
52 99 3
53 16 2
54 21 2
55 21 1
56 16 1
57 10 1
58 22 2

如果您需要每个电话的更多详细信息,可以添加子查询:

SELECT
  Phone,
  Sum(Price) as Total,
  Count(Purchases) as Purchase_Count,
  (SELECT TOP 1 Price
   FROM supportContacts sc2
   WHERE sc2.phone=sc1.phone
   ORDER BY fecha DESC
  ) as Most_Recent
FROM supportContacts sc1
GROUP BY Phone
ORDER BY Phone

或者,对于我最终解决的实际要求:)

SELECT
  Phone,
  Sum(Price) as Total,
  Count(Purchases) as Purchase_Count,
  (SELECT Purchases
   FROM supportContacts sc2
   WHERE sc2.phone=sc1.phone
   AND sc2.Fecha=
     (SELECT Max(Fecha)
      FROM supportContacts sc3
      WHERE sc3.phone=sc1.phone
     )
  ) as Last_Purchase
FROM supportContacts sc1
GROUP BY Phone
ORDER BY Phone

..这开始变得相当笨拙,可能有优化的可能,但我失去了玩的意愿......哈哈

但是感谢您尝试以这种方式进行的大脑锻炼:)

编辑
如果是我,我可能会这样做......
http://sqlfiddle.com/#!6/7b36f/98

With PhoneGroup as
( SELECT
    Phone,
    Sum(Price) as Total_Price,
    Max(Fecha) as Last_Fecha
  FROM supportContacts
  GROUP BY Phone
)
SELECT
  Phone, Total_Price,
 (SELECT Purchases
  FROM supportContacts sc2
  WHERE sc2.phone=PhoneGroup.phone
    AND sc2.Fecha=PhoneGroup.Last_Fecha
 ) as Last_Purchase
FROM PhoneGroup
ORDER BY Phone
于 2013-04-11T16:29:16.130 回答