我有一个查询,它返回如下数据:
Event | Sum | Date
sent | 400 | 1/1/12
open | 200 | 1/1/12
click | 50 | 1/1/12
sent | 300 | 1/8/12
open | 150 | 1/8/12
click | 30 | 1/8/12
SQL查询:
select event, sum(thecount), rundate
from send_open_click_counts
group by event, rundate
order by rundate, event desc
要将这些值发送到谷歌可视化 api 以呈现图形,我需要像这样排列这些值:
['date' , 'sent' , 'opened' , 'clicked']
['1/1/12', '400' , '200' , '50']
['1/8/12', '300', '150' , '30']
我对这些东西不是很熟悉,但对我来说这是按日期旋转的。
这是我用来模拟原始 SQL 的 linq 查询
var dbLinqObj= from r in db.SEND_OPEN_CLICK_COUNTS
group r by new { r.EVENT, r.RUNDATE } into g
select new {
EVENT = g.Key.EVENT,
THECOUNT = g.Sum(r => r.THECOUNT),
RUNDATE = g.Key.RUNDATE
} ;
dbLinqObj= dbLinqObj.OrderBy(r => r.RUNDATE);
==== 编辑 ==== 找到解决方案 =====
在深入研究并从评论中获得一些建议后,我发现了一个使用 LINQ 的优雅解决方案。
这是正确旋转结果的 LINQ,以便可以轻松地将其转换为 JSON 字符串。
var query = from q in db.SEND_OPEN_CLICK_COUNTS
group q by q.RUNDATE into g
select new
{
Date = g.Key,
Send = g.Where(x => x.EVENT == "sent").Sum(x => x.THECOUNT),
Open = g.Where(x => x.EVENT == "opened").Sum(x => x.THECOUNT),
Click = g.Where(x => x.EVENT == "clicked").Sum(x => x.THECOUNT)
};