我在SQL Server中有一个表,我想计算每天的记录数,例如,你想象我们有两个日期" 2017/12/01"到" 2018/01/12"
Date New York LA Boston Chicago Cleveland
===================================================================
2017/12/01 10 800 820 245 90
2017/12/02 200 30 120 112 356
2017/12/03 500 44 58 34 321
2017/12/04 120 540 98 67 651
.......
此外,city还有一个代码,其列名为CityCode
,例如
new york = 1 , LA = 2 , Boston = 3 , Chicago = 4 , Cleveland = 5
但日期栏中有通知。实际上,我的日期列基于字符串格式而不是日期格式。我已经编写了一些代码,但它将字符串日期转换为DateTime格式时有例外。
此代码只返回纽约市的结果。您是否认为应该为其他城市重复此代码5次?
public class OrderDateSummary
{
public string Date { get; set; }
public int Total { get; set; }
public int Code { get; set; }
}
var startDate = Convert.ToDateTime(FromDate);
var endDate = Convert.ToDateTime(ToDate);
var newYork = db.tbl_bar
.Where(t => startDate <= DateTime.ParseExact(t.date_rec_slash, "yyyy/MM/dd", null) && DateTime.ParseExact(t.date_rec_slash, "yyyy/MM/dd", null) <= endDate && t.CityCode == 1)
.GroupBy(t => t.date_rec_slash, (date, values) =>
new OrderDateSummary()
{
Date = date,
Total = values.Count(),
})
.OrderBy(summary => summary.Date)
.ToList();
答案 0 :(得分:2)
SELECT date::DATE, count(citycode) as total,
CASE
WHEN citycode = 1 THEN 'New York'
WHEN citycode = 2 THEN 'LA'
WHEN citycode = 3 THEN 'Boston'
WHEN citycode = 4 THEN 'Chicago'
WHEN citycode = 5 THEN 'Cleveland'
END
FROM YOUR_TABLE
WHERE date::DATE between '2017/12/01' AND '2017/12/31'
GROUP BY date::DATE, citycode
ORDER BY date desc;
对于SQL Server,您可能必须使用
Cast(date as datetime)
代替
date::DATE
。
要用作存储过程,请执行以下操作:
USE YOUR_DATABASE_NAME
GO
CREATE PROCEDURE ANY_PROCEDURE_NAME
AS
now_put_sql_here
GO
运行它,它将创建一个名为&#34; ANY_PROCEDURE_NAME&#34;的存储过程。在&#34; YOUR_DATABASE_NAME&#34;