获得每组中列值的中位数

时间:2016-02-15 01:21:41

标签: sqlite group-by median

我有一个包含user_id,movie_id,rating的表。这些都是INT,评级范围从1-5。

我想获得中位数评分并按user_id分组,但我在执行此操作时遇到了一些麻烦。

目前我的代码是:

SELECT AVG(rating)
FROM (SELECT rating
      FROM movie_data
      ORDER BY rating
      LIMIT 2 - (SELECT COUNT(*) FROM movie_data) % 2
      OFFSET (SELECT (COUNT(*) - 1) / 2
              FROM movie_data));

然而,这似乎返回了所有评级的中值。如何通过user_id对此进行分组,以便我可以看到每个用户的中位数评分?

3 个答案:

答案 0 :(得分:1)

以下给出了所需的中位数:

DROP TABLE IF EXISTS movie_data2;
CREATE TEMPORARY TABLE movie_data2 AS
SELECT user_id, rating FROM movie_data order by user_id, rating;

SELECT a.user_id, a.rating FROM (
SELECT user_id, rowid, rating
FROM movie_data2) a JOIN (
SELECT user_id, cast(((min(rowid)+max(rowid))/2) as int) as midrow FROM movie_data2 b
GROUP BY user_id
) c ON a.rowid = c.midrow
;

逻辑很简单,但代码没有被美化。鉴于鼓励或评论,我会改进它。简而言之,诀窍是使用SQLite的rowid

答案 1 :(得分:0)

这不容易实现,因为SQLite不允许相关子查询引用LIMIT / OFFSET子句中的外部值。

user_id的WHERE子句添加到所有三个子查询中,并为每个用户ID执行它们。

答案 2 :(得分:-1)

[HttpPost]
[Authorize(Roles = "ADM")]
public ActionResult UpdateDetails(Guid id, int prodqty)
{
  // Entities.BeginTransaction here;
  BusinessLayer.Orders blorder = new BusinessLayer.Orders();
  CommonLayer.ORDERDETAIL orderdetail = blorder.GetOrderDetailByDetailId(id);
  blorder.UpdateOrderDetails(orderdetail, prodqty);

  /*Now, check if your data can be Saved by triggering SaveChanges()
   if(Entities.SaveChanges)
  {
    Entities.Commit
  }else
  {
    Entities.Rollback
  } */

  return RedirectToAction("ViewOrder");
}