按结果将组聚合成一行

时间:2018-04-16 19:36:13

标签: mysql sql oracle

我试图在多个表上执行sql查询,并在按项目ID分组时对某些值进行计数和平均。这是我的SQL查询:

select p.id,
       count(e.id) as count, 
       avg(opened) as opened,
       avg(read_email) as clicked,
       avg(started_video) as started_watching,
       sum(views) as views
from   projects p
       inner join guests g
       on g.project_id = p.id
       inner join videos v
       on v.guest_id = g.id
       inner join emails e
       on e.video_id=v.id
group by p.id;

这是返回的表:

id count opened clicked started_watching views
-- ----- ------ ------- ---------------- -----
 2     1 1.0000  1.0000           1.0000     1
 3     3 0.3333  0.3333           0.3333     2

我想进一步聚合这些结果,理想情况下只返回一行。例如,我希望能够计算(打开)/计数为avgOpened,计数(点击)/计数为avgClicked,count(started_watching)/计数为avgWatched,count(views)为totalViews等...

我想知道在sql中是否有一种优雅的方法来执行此操作,或者是否应该以编程方式完成此处理。还想知道在sql中执行此操作是否有效。

1 个答案:

答案 0 :(得分:0)

您可以将其设为连接的子查询,这样您就可以使用此查询的结果进一步计算和分组:

public static Regex regexes = new Regex("(\\<script(.+?)\\</script\\>)|(\\<iframe(.+?)\\</iframe\\>)");

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    string str = (string)value;

    if (str != null)
    {
        if (regexes.IsMatch(str)) {                 
            return new ValidationResult($"A potentially dangerous value was detected from request {validationContext.Name}: {str}");
        }
    }

    return ValidationResult.Success;
}