【问题标题】:ORDER BY maximum with grouped byORDER BY 最大值与分组依据
【发布时间】:2013-05-24 04:28:14
【问题描述】:

如下表,

RECORD
---------------------
NAME            VALUE
---------------------
   Bill Clinton   100
   Bill Clinton    95
   Bill Clinton    90
Hillary Clinton    90
Hillary Clinton    95
Hillary Clinton    85
Monica Lewinsky    70
Monica Lewinsky    80
Monica Lewinsky    90

我可以使用 JPA(JPQL 或 Criteria)选择以下输出吗?

   Bill Clinton   100
Hillary Clinton    95
Monica Lewinsky    90

我的意思是,ORDER BY 最多 VALUE 分组 NAME

【问题讨论】:

    标签: mysql sql jpa criteria jpql


    【解决方案1】:

    查询本身

    SELECT  Name,
            MAX(value) value
    FROM    record
    GROUP BY Name
    ORDER BY Value DESC
    

    输出:

    |            NAME | VALUE |
    ---------------------------
    |    Bill Clinton |   100 |
    | Hillary Clinton |    95 |
    | Monica Lewinsky |    90 |
    

    SQLFiddle

    我不是 jpa 方面的专家,但介于这几行之间的东西可能会起作用

    List<Object[]> results = entityManager
            .createQuery("SELECT  Name, MAX(value) maxvalue FROM record GROUP BY Name ORDER BY Value DESC");
            .getResultList();
    for (Object[] result : results) {
        String name = (String) result[0];
        int maxValue = ((Number) result[1]).intValue();
    }
    

    【讨论】:

    • "使用 JPA(JPQL 或标准)"?
    • @eggyal 更新了答案
    【解决方案2】:

    因为 JPQL 查询对实体进行操作,所以假设以下映射:

    @Entity
    @Table(name="your_table")
    public class YourEntity {
        @Id private int id;
        private String name;
        private int value;
        ...
    }
    

    对于这样的映射查询如下:

    SELECT e.name, MAX(e.value)
    FROM YourEntity e
    GROUP BY e.name
    ORDER BY MAX(e.value) DESC
    

    这种查询的结果是对象数组列表。数组中的第一个元素是名称,第二个元素是值(如 select)。

    【讨论】:

      【解决方案3】:

      使用标准:

      CriteriaQuery<Person> q = cb.createQuery(Person.class);
      Root<Person> p = q.from(Person.class);
      q.select(p.get("name"), cb.max(p.get("value")));
      q.groupBy(p.get("name"));
      q.orderBy(cb.desc(cb.max(p.get("value"))));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-17
        • 2017-08-22
        • 2015-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-26
        相关资源
        最近更新 更多