我的数据格式为
+----------+-------------+
|Customerid|DateofJoining|
+----------+-------------+
|1 |aug 1 |
+----------+-------------+
|2 |aug 1 |
+----------+-------------+
|3 |aug 10 |
+----------+-------------+
|4 |aug 10 |
+----------+-------------+
|5 |aug 10 |
+----------+-------------+
|6 |sept 5 |
+----------+-------------+
所以我想展示结果 作为时间进展的客户数量
+--------------+------+
|TotalCustomers|Date |
+--------------+------+
|2 |Aug 1 |
+--------------+------+
|5 |Aug 10|
+--------------+------+
|6 |Sept 5|
+--------------+------+
我该怎么做。
通过分组,我可以在任何给定日期显示总客户,但不会在此之前显示总和。我该怎么做?
我试过了:
SELECT COUNT(numcustomersjoined), dateofjoining
FROM foo
GROUP BY dateofjoining
但这对我不起作用。
答案 0 :(得分:2)
您没有包含sql-server的版本。这适用于sqlserver-2012:
create table foo(Customerid int, DateofJoining date)
insert into foo values
(1,'2014-08-01'),(2,'2014-08-01'),(3,'2014-08-10'),
(4,'2014-08-10'),(5,'2014-08-10'),(6,'2014-09-05')
SELECT
DateofJoining,
SUM(COUNT(*)) OVER (ORDER BY dateofjoining) CumulativeTotal
FROM foo
GROUP BY DateofJoining
结果:
DateofJoining CumulativeTotal
2014-08-01 2
2014-08-10 5
2014-09-05 6
答案 1 :(得分:1)
您的输出显示您希望在特定日期加入最高customerId
。
为此,您可以使用max
功能。
select max(Customerid), dateofjoining from foo group by dateofjoining
答案 2 :(得分:1)
SELECT MAX(Customerid), dateofjoining FROM foo GROUP BY dateofjoining;
试试这个......
答案 3 :(得分:0)
您正在寻找 running total 。让我们来讨论this scenario:
create table t( Customerid int, DateofJoining date );
insert into t values
(1 , '2014-08-01' ),
(12, '2014-08-01' ),
(53, '2014-08-10' ),
(14, '2014-08-10' ),
(5 , '2014-08-10' ),
(96, '2014-09-05' )
然后你可以使用这个非等值的运行总计计数:
;with
slots as
(select
distinct DateofJoining
from t
)
select
count(*) as n,
slots.DateofJoining
from
t inner join slots
on t.DateofJoining <= slots.DateofJoining --non equijoin
group by
slots.DateofJoining
<强> Results 强>:
| N | DATEOFJOINING |
|---|---------------|
| 2 | 2014-08-01 |
| 5 | 2014-08-10 |
| 6 | 2014-09-05 |