I am trying to run following query from SpringBoot repository
#Query("select * from c where id1 =?0 and id2 =?1 and id3 =?2 and c1 =?3 and year in :year and month in :month and day in :day and hour in :hour and minute in :minute"
public List<Counter> findCWithinRangeIn(
#Param("id1") String id1,
#Param("id2") String id2,
#Param("id3") String id3,
#Param("c1") String c1,
#Param("year") List<Integer> year,
#Param("month") List<Integer> month,
#Param("day") List<Integer> day,
#Param("hour") List<Integer> hour,
#Param("minute") List<Integer> minute);
But always hitting error : Invalid amount of bind variables.
Please suggest on how to proceed further.
Note: I did follow Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause but it did not work for me.
I want to execute something like:
select * from c
where id1 ="xyz" and
id2 ="abc" and
id3 ="pqr" and
c1 = "Sample" and
year IN (2016,2017) and
month IN (9,10,11) and
day IN (19,20,24) and
hour IN (23, 13) and
minute IN (50, 51, 53)
If you don't need to specify custom query this could work for you (based on method name)
public List<Counter> findAllById1AndId2AndId3AndC1AndYearInAndMonthInAndDayInAndHourInAndMinuteIn(String id1, STring id2, String id3, String c1, List<Long> years, List<Long> months, List<Long> days, List<Long> hours, List<Long> minutes)
note: in your Counter entity the field's names must match the names of attribute names specified in method name.
Related
I have a table like below
year int
month int
symbol string
company_name string
sector string
sub_industry string
state string
avg_open double
avg_close double
avg_low double
avg_high double
avg_volume double
The field starting with avg_ refers to the average value in a month for a year. I need to find for each sector the year in which average of avg_close is the lowest.
I tried to do something like below
SELECT sector, year FROM
(
SELECT sector, year, RANK() OVER (ORDER BY s2.yearly_avg_close) AS RANK FROM
( SELECT year,sector, AVG(avg_close) AS yearly_avg_close FROM stock_summary GROUP BY sector, year) s2
) s1
WHERE
s1.RANK = 1;
But this is printing just one sector and year like below
Telecommunications Services 2010
I am new to hive and playing around with some toy schemas. Can someone let me know what should be the correct way of solving this?
Hive Version - 1.1.0
Include sector into the partition by in the rank() function:
SELECT sector, year, RANK() OVER (partition by sector ORDER BY s2.yearly_avg_close) AS RANK
Add year as well if you need rank per each sector and year
Read also this explanation how rank works: https://stackoverflow.com/a/55909947/2700344
I have a table with 5 columns like this:
id, name, firstName, job, number
There are many records in this table. Now, imagine these records:
- 1 Konan toto doctor 45
- 2 Konan tata doctor 50
- 3 Konan toto doctor 60
- 4 simba popo police 44
- 5 simba tata police 88
- 6 pikar popo doctor 99
- 7 simba popo doctor 72
now I want to find only record which job is doctor and get record with no duplicate in (name,firstName)
(if we have many records with same name + lastName we return only one record , let say anyone)
the result will be
- 1 Konan toto doctor 45
- 2 Konan tata doctor 50
- 6 pikar popo doctor 99
- 7 simba popo doctor 72
the record with id 3 is removed because there is duplicate on (name,firstName) the others because we only need job = doctor
What is the Hibernate Query to get the desired results ?
I'm not sure why this has to be done with JPQL, it seems rather difficult and produce an inefficient query that probably requires a self join. Here's a relatively simple Oracle SQL based solution
SELECT
MAX(id) KEEP (DENSE_RANK FIRST ORDER BY id) AS id,
name,
firstName,
MAX(job) KEEP (DENSE_RANK FIRST ORDER BY id) AS job,
MAX(number) KEEP (DENSE_RANK FIRST ORDER BY id) AS number
FROM t
WHERE job = 'doctor'
GROUP BY name, firstName
A more standards compliant solution using window functions:
SELECT
FROM (
SELECT
id, name, firstName, job, number,
ROW_NUMBER() OVER (PARTITION BY name, firstName ORDER BY id) rn
FROM t
WHERE job = 'doctor'
) t
WHERE rn = 1
This is a special case of the top N per category problem. I recommend using a native query, which you can still map to entities if you really need to.
Somehow I'm running in circles for two days! I have MySQL Database and comments table in witch I have id, user_id, date, published_at, body, likes and dislikes. How to limit user for max 10 comments per day. Of course I have user table.
I know I have somehow to count number of comments for certain date and put it in security context but I don't know how. I've tried with some native queries in
Repository like:
#Query(value = "select count from comments WHERE published_at=?1 AND user_id=?2", nativeQuery = true)
public int brojPostovaPoDanuPoUseru(Date datum, Integer user_id);
I guess I should find logged user name from SecurityContext and after that find his id, but then again what if there are two users with a same name, and where to use SecurityContext to find this.
At least some guidelines please :)
You can implement this on database level. My idea would be to save the time in seconds in date ( using Java: System.currentTimeMillis()). Then when you query by the user id, you can sort the results by date in descending order and filter for the top 10. Then you would pick the smallest number in date and check if it was less then 24h ago, if so you could then return an exception.
This would be an example query:
select * from (SELECT * FROM `comments` where comments.user_id=?1 ORDER BY `comments`.`date` DESC limit 10) as c order by c.date ASC limit 1
Let's say you saved date in secods using System.currentTimeMillis() / 1000. Now with the query result you would first calculate the seconds in hours and then in a day. This results in 86400 seconds. Now you would calculate the current time in seconds and extract it with the 24h in seconds as calculated before. And then you would check if this calculated result is smaller than the value of date this would indicate that the last 10th comment was made within the 24 hours.
This is the sample code in your repository:
#Query("select * from (SELECT * FROM `comments` where comments.user_id=?1 ORDER BY `comments`.`date` DESC limit 10) as c order by c.date ASC limit 1", nativeQuery=true)
public Comments getLastTenthComment(int userId);
This is the sample code in your service:
public boolean isAllowedToComment(int userId){
Comment comment = repository.getLastTenthComment(userId);
int dayInSeconds = 86400;
long currentTime = System.currentTimeMillis() / 1000;
long yesterdayInSeconds = currentTime - dayInSeconds;
if(comment.getDate() >= yesterdayInSeconds){
return false;
}
return true;
}
I need to get a count of items by date from field1 grouped by last update time. What I am looking for is how many times an item from field1 appears on a specific date for the last 30 days where field 2 = 0. This will be run every day so the date will roll. Field1 will be a number >0, field2 will be any number (negative and positive), last_upd_time will be a system time when the last update occurred. I don't need the time, only the date. My current query that returns all of the data is:
select field1, field2, trunc(last_upd_time)
from table
where field2 = '0' and last_upd_time >= SYSDATE - 30
I have attempted to use count, group by, and group by/having. Not saying I was using them correctly, but I did try.
Try this:
SELECT TO_CHAR(last_upd_time,'DD-MM-YYYY') last_upd_time, COUNT(DISTINCT field1)
FROM table WHERE field2='0' AND
last_upd_time>=SYSDATE - INTERVAL '30' DAY
GROUP BY TO_CHAR(last_upd_time,'DD-MM-YYYY');
I'm struggling writing PL/SQL (I'm new to PL/SQL) and I'm not sure how to structure SQL and loops for something like this.
I have 128 lines of SQL to create something like the following cursor:
ID Course Grade Attend? Date
123 MATH091 B Y 5/15
123 BIOL101 F N 3/10
123 ENGL201 W Y 1/2
456 MATH091 A Y 5/16
456 CHEM101 C Y 5/16
456 POLS301 NULL NULL NULL
With each ID, I need to several comparisons across the courses (e.g. which has the latest date, or were all courses attended). These comparisons need to be done in a certain order so that when they hit one that is true, they are flagged with a code and excluded from subsequent comparisons.
For example:
All courses attended? If true, output as attended and remove from next steps.
Find and store the latest date with a passing grade.
Find and store the latest date with a non-passing grade.
Is the later date after a course with a null grade? If true, output as coming back and remove from next steps.
Etc.
Each condition can be easily written in a SQL, but I don't know/understand the appropriate structure to loop through this process.
Is there syntax that can accomplish this easily?
We're on Oracle 11g and we do not have permissions to write to a temporary table.
I don't think you need PL/SQL for this. Except for the "unknown" requirement "etc." this can all be done in a single SQL statement:
Something like:
select id, course, grade, attended, attendance_date,
count(distinct case when attended = 'Y' then course end) over (partition by id) courses_attended,
count(distinct course) over () as total_courses,
case
when count(distinct case when attended = 'Y' then course end) over (partition by id) = count(distinct course) over () then 'yes'
else 'no'
end as all_courses_attended,
max(case when attended <> 'F' then attendance_date else null end) over (partition by id) as latest_passing_date,
max(case when attended = 'F' then attendance_date else null end) over (partition by id) as latest_non_passing_date
from attendees
order by id;
Btw: the attended column is not necessary if you have an attendance_date. If that date is not NULL than obviously the student attended the course. Otherwise she/he didn't.
Of course I have no idea what the "etc." steps should do though....
SQLFiddle example: http://sqlfiddle.com/#!4/e7c95/1