HQL / SQL - 如果有两个列(具有不同的名称)作为单个分组,如何分组

时间:2018-01-24 00:45:23

标签: sql oracle hql

我有以下问题,例如(我的表和错误的HQL):

+--------------------+
|    DATE    | COUNT |
+------------+-------+
| 2018-01-24 | 77    | -- count dateInserted and Updated together
| 2018-01-23 | 16    | -- the same thing
| 2018-01-22 | 22    | -- just dateInserted
|    etc.    | etc.  |
+------------+-------+

我希望输出像这张表。

-- SQL attempt (dont mention hql look):
-- And there is problem with first two grouped rows which is not together (2018-01-24 | 27 dateInsered) and (2018_01_24 | 50 dateUpdated)
SELECT datee, summ FROM
(
SELECT to_char(student.dateInserted, 'YYYY-MM-DD') as datee, count(student.dateInserted) as summ
FROM STUDENTS student
INNER JOIN TEACHERS teacher ON (student.teacher_id == teacher.id)
WHERE (student.age > 20 AND student.dateInserted < SYSDATE)
UNION ALL
SELECT to_char(student.dateUpdated, 'YYYY-MM-DD') as datee, count(student.dateUpdated) as summ
FROM STUDENTS student
INNER JOIN TEACHERS teacher ON (student.teacher_id == teacher.id)
WHERE (student.age < 20 AND student.dateUpdated  > SYSDATE-2)
)
GROUP BY datee
ORDER BY datee;

问题是:如何在HQL中使用?在SQL中怎么做?
在HQL中我尝试了CASE,但没有成功。
在SQL中我尝试了内部的SELECT和UNION ALL,但也没有成功。

{{1}}

任何帮助表示赞赏。请不要在代码中提及错别字,那个例子没有多大意义:)知道...谢谢

1 个答案:

答案 0 :(得分:1)

我没看到teacher与此有什么关系。我认为这样做你想要的:

SELECT yyyymmdd, SUM(num_inserted) as num_inserted,
       SUM(num_updated) as num_updated,
       SUM(num_inserted + num_updated) as both
FROM ((SELECT TO_CHAR(s.dateInserted, 'YYYY-MM-DD') as yyyymmdd, COUNT(*) as num_inserted, 0 as num_updated
       FROM STUDENTS s
       WHERE (s.age > 20 AND s.dateInserted < SYSDATE) OR
             (s.age < 20 AND s.dateUpdated  > SYSDATE - 2)
       GROUP BY TO_CHAR(s.dateInserted, 'YYYY-MM-DD')
      ) UNION ALL
      (SELECT TO_CHAR(s.dateUpdated, 'YYYY-MM-DD'), 0, COUNT(*) as num_updated
       FROM STUDENTS s
       WHERE (s.age > 20 AND s.dateInserted < SYSDATE) OR
             (s.age < 20 AND s.dateUpdated  > SYSDATE - 2)
       GROUP BY TO_CHAR(s.dateUpdated, 'YYYY-MM-DD')
      )
     ) s
GROUP BY yyyymmdd
ORDER BY yyyymmdd;