我有以下需要
我有一个记录表,记录每天生成的som潜在客户。
现在,我需要在过去10天内针对每天的潜在客户数量进行报告。
让我们说这个表是这样的:
tbl_leads
id int,
first_name nvarchar(100),
last_name nvarchar(100),
created_date datetime
我需要计算每天的潜在客户数量,总计10天。 所以结果集看起来应该是这样的:
counted_leads | count_date
5 | 2009-04-30
7 | 2009-04-29
5 | 2009-04-28
7 | 2009-04-27
......等等
任何人都知道如何以最好的方式做到这一点? 我目前的解决方案是在c#中使用foreach进行迭代,但我非常希望将它交给sql服务器而不是sp。
答案 0 :(得分:31)
您可以使用:
Select
count(created_date) as counted_leads,
created_date as count_date
from
table
group by
created_date
答案 1 :(得分:5)
您的created_date字段为datetime
,因此如果您想按日期排序,则需要在分组工作之前剥去时间:
SELECT COUNT(created_date), created_date
FROM table
WHERE DATEDIFF(created_date, getdate()) < 10
GROUP BY convert(varchar, created_date, 101)
答案 2 :(得分:2)
最有效的方法是按整数进行聚合,然后转换回日期时间进行演示。
select
cast(daybucket - 1 as datetime) as count_date,
counted_leads
from
(select
cast(created_date as int) as DayBucket,
count(*) as counted_leads
from mytable
group by cast(created_date as int) ) as countByDay
答案 3 :(得分:2)
当你将一个DateTime转换为一个int时,它会在中午“截断”,你可能想要将这一天剥离出去
cast(DATEADD(DAY, DATEDIFF(DAY, 0, created_date), 0) as int) as DayBucket
答案 4 :(得分:1)
Select count(created_date) total
, created_dt
from table
group by created_date
order by created_date desc
答案 5 :(得分:1)
CREATE PROCEDURE [dbo].[sp_Myforeach_Date]
-- Add the parameters for the stored procedure here
@SatrtDate as DateTime,
@EndDate as dateTime,
@DatePart as varchar(2),
@OutPutFormat as int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
Declare @DateList Table
(Date varchar(50))
WHILE @SatrtDate<= @EndDate
BEGIN
INSERT @DateList (Date) values(Convert(varchar,@SatrtDate,@OutPutFormat))
IF Upper(@DatePart)='DD'
SET @SatrtDate= DateAdd(dd,1,@SatrtDate)
IF Upper(@DatePart)='MM'
SET @SatrtDate= DateAdd(mm,1,@SatrtDate)
IF Upper(@DatePart)='YY'
SET @SatrtDate= DateAdd(yy,1,@SatrtDate)
END
SELECT * FROM @DateList
END
只需输入此代码并以这种方式调用SP
exec sp_Myforeach_Date @SatrtDate='03 Jan 2010',@EndDate='03 Mar 2010',@DatePart='dd',@OutPutFormat=106
答案 6 :(得分:1)
我有类似的问题,但我涉及一个列Convert(date,mydatetime)。我必须改变最佳答案如下:
Select
count(created_date) as counted_leads,
Convert(date,created_date) as count_date
from table
group by Convert(date,created_date)