i have following problem, example (my tables, and wrong HQL):
SELECT to_char(student.dateInserted, 'YYYY-MM-DD'), count(student.dateInserted)
FROM STUDENTS student
INNER JOIN TEACHERS teacher ON (student.teacher_id == teacher.id)
WHERE (student.age > 20 AND student.dateInserted < SYSDATE)
OR (student.age < 20 AND student.dateUpdated > SYSDATE-2)
GROUP BY to_char(student.dateInserted, 'YYYY-MM-DD')
ORDER BY to_char(student.dateInserted, 'YYYY-MM-DD');
I would like to have output like this table.
+--------------------+
| 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. |
+------------+-------+
Question is: How to that in HQL? And how to that in SQL?
In HQL I tried CASEs, but without succes.
In SQL I tried outer SELECT and UNION ALL inside, but also without succes.
-- 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;
Any help appreciated. Please dont mention typos in code and that example doesnt have much sense :) know ... thanks
I don't see what teacher
has to do with this. I think this does what you want:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.