Select most reviewed courses starting from courses having at least 2 reviews - postgresql
I'm using Flask-SQLAlchemy with PostgreSQL. I have the following two models:
class Course(db.Model):
id = db.Column(db.Integer, primary_key = True )
course_name =db.Column(db.String(120))
course_description = db.Column(db.Text)
course_reviews = db.relationship('Review', backref ='course', lazy ='dynamic')
class Review(db.Model):
__table_args__ = ( db.UniqueConstraint('course_id', 'user_id'), { } )
id = db.Column(db.Integer, primary_key = True )
review_date = db.Column(db.DateTime)#default=db.func.now()
review_comment = db.Column(db.Text)
rating = db.Column(db.SmallInteger)
course_id = db.Column(db.Integer, db.ForeignKey('course.id') )
user_id = db.Column(db.Integer, db.ForeignKey('user.id') )
I want to select the courses that are most reviewed starting with at least two reviews. The following SQLAlchemy query worked fine with SQlite:
most_rated_courses = db.session.query(models.Review, func.count(models.Review.course_id)).group_by(models.Review.course_id).\
having(func.count(models.Review.course_id) >1) \ .order_by(func.count(models.Review.course_id).desc()).all()
But when I switched to PostgreSQL in production it gives me the following error:
ProgrammingError: (ProgrammingError) column "review.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT review.id AS review_id, review.review_date AS review_...
^
'SELECT review.id AS review_id, review.review_date AS review_review_date, review.review_comment AS review_review_comment, review.rating AS review_rating, review.course_id AS review_course_id, review.user_id AS review_user_id, count(review.course_id) AS count_1 \nFROM review GROUP BY review.course_id \nHAVING count(review.course_id) > %(count_2)s ORDER BY count(review.course_id) DESC' {'count_2': 1}
I tried to fix the query by adding models.Review in the GROUP BY clause but it did not work:
most_rated_courses = db.session.query(models.Review, func.count(models.Review.course_id)).group_by(models.Review.course_id).\
having(func.count(models.Review.course_id) >1) \.order_by(func.count(models.Review.course_id).desc()).all()
Can anyone please help me with this issue. Thanks a lot
SQLite and MySQL both have the behavior that they allow a query that has aggregates (like count()) without applying GROUP BY to all other columns - which in terms of standard SQL is invalid, because if more than one row is present in that aggregated group, it has to pick the first one it sees for return, which is essentially random.
So your query for Review basically returns to you the first "Review" row for each distinct course id - like for course id 3, if you had seven "Review" rows, it's just choosing an essentially random "Review" row within the group of "course_id=3". I gather the answer you really want, "Course", is available here because you can take that semi-randomly selected Review object and just call ".course" on it, giving you the correct Course, but this is a backwards way to go.
But once you get on a proper database like Postgresql you need to use correct SQL. The data you need from the "review" table is just the course_id and the count, nothing else, so query just for that (first assume we don't actually need to display the counts, that's in a minute):
most_rated_course_ids = session.query(
Review.course_id,
).\
group_by(Review.course_id).\
having(func.count(Review.course_id) > 1).\
order_by(func.count(Review.course_id).desc()).\
all()
but that's not your Course object - you want to take that list of ids and apply it to the course table. We first need to keep our list of course ids as a SQL construct, instead of loading the data - that is, turn it into a derived table by converting the query into a subquery (change the word .all() to .subquery()):
most_rated_course_id_subquery = session.query(
Review.course_id,
).\
group_by(Review.course_id).\
having(func.count(Review.course_id) > 1).\
order_by(func.count(Review.course_id).desc()).\
subquery()
one simple way to link that to Course is to use an IN:
courses = session.query(Course).filter(
Course.id.in_(most_rated_course_id_subquery)).all()
but that's essentially going to throw away the "ORDER BY" you're looking for and also doesn't give us any nice way of actually reporting on those counts along with the course results. We need to have that count along with our Course so that we can report it and also order by it. For this we use a JOIN from the "course" table to our derived table. SQLAlchemy is smart enough to know to join on the "course_id" foreign key if we just call join():
courses = session.query(Course).join(most_rated_course_id_subquery).all()
then to get at the count, we need to add that to the columns returned by our subquery along with a label so we can refer to it:
most_rated_course_id_subquery = session.query(
Review.course_id,
func.count(Review.course_id).label("count")
).\
group_by(Review.course_id).\
having(func.count(Review.course_id) > 1).\
subquery()
courses = session.query(
Course, most_rated_course_id_subquery.c.count
).join(
most_rated_course_id_subquery
).order_by(
most_rated_course_id_subquery.c.count.desc()
).all()
A great article I like to point out to people about GROUP BY and this kind of query is SQL GROUP BY techniques which points out the common need for the "select from A join to (subquery of B with aggregate/GROUP BY)" pattern.
Related
Use postgresql query results to form another query
I am trying to select from one table using the select result from another table. I can run this in two queries but would like to optimize it into just one. First query.. Select ids where matching other id select id from lookuptable where paid = '547' This results in something like this 6316352 6316353 6318409 6318410 6320468 6320469 6320470 6322526 6322527 6324586 6324587 6326648 I would like to then use this result to make another selection. I can do it manually like below. Note, there could be many rows with these values so I've been using a IN statement select * from "othertable" where id in (6316352,6316353,6318409,6318410,6320468,6320469,6320470,6322526,6322527,6324586,6324587,6326648);
select ot.* from "othertable" as ot join lookuptable as lt on ot.id = lt.id where lt.paid = '547'
The IN operator supports not just value lists but also subqueries, so you can literally write select * from "othertable" where id in (select id from lookuptable where paid = '547');
How to set a Where clause on the top (parent) level in PostgreSQL?
I'm relatively new to PostgreSQL. My issue is that I have apartments with their reservations and I need select those are available (don't have reservations) for a given range. Reservations table has fields apartmentId (which references Apartments table), userId and datesReserved which is tstzrange. For these purposes I'm doing this query: SELECT * FROM apartments JOIN appointments ON appointments.aparmentId = apartments.id WHERE NOT(datesreserved && '[2020-12-15T15:00:00.000Z, 2020-12-17T16:00:00.000Z)'); But instead I'm getting filtered appointments - those that do not contain the value [2020-12-15T15:00:00.000Z, 2020-12-17T16:00:00.000Z). As far as I researched there are top-level where and inner-level, and as far as I understand this query should give me top-level results - those apartments that do not contain the provided range. Am I understanding correctly in this case?
I think you need NOT EXISTS here. As it is, you don't have a "top level", the tables are peers. SELECT * FROM apartments WHERE NOT EXISTS ( SELECT 1 from appointments WHERE appointments.aparmentId = apartments.id and datesreserved && '[2020-12-15T15:00:00.000Z, 2020-12-17T16:00:00.000Z)' );
Conditional WHERE clause in KDB?
Full Query: {[tier;company;ccy; startdate; enddate] select Deal_Time, Deal_Date from DEALONLINE_REMOVED where ?[company = `All; 1b; COMPANY = company], ?[tier = `All;; TIER = tier], Deal_Date within(startdate;enddate), Status = `Completed, ?[ccy = `All;1b;CCY_Pair = ccy]} Particular Query: where ?[company = `All; 1b; COMPANY = company], ?[tier = `All; 1b; TIER = tier], What this query is trying to do is to get the viewstate of a dropdown. If there dropdown selection is "All", that where clause i.e. company or tier is invalidated, and all companies or tiers are shown. I am unsure if the query above is correct as I am getting weird charts when displaying them on KDB dashboard.
What I would recommend is to restructure your function to make use of the where clause using functional qSQL. In your case, you need to be able to filter based on certain input, if its "All" then don't filter else filter on that input. Something like this could work. /Define sample table DEALONLINE_REMOVED:([]Deal_time:10#.z.p;Deal_Date:10?.z.d;Company:10?`MSFT`AAPL`GOOGL;TIER:10?`1`2`3) /New function which joins to where clause {[company;tier] wc:(); if[not company=`All;wc:wc,enlist (=;`Company;enlist company)]; if[not tier=`All;wc:wc,enlist (=;`TIER;enlist tier)]; ?[DEALONLINE_REMOVED;wc;0b;()] }[`MSFT;`2] If you replace the input with `All you will see that everything is returned.
The full functional select for your query would be as follows: whcl:{[tier;company;ccy;startdate;enddate] wc:(enlist (within;`Deal_Date;(enlist;startdate;enddate))),(enlist (=;`Status;enlist `Completed)), $[tier=`All;();enlist (=;`TIER;enlist tier)], $[company=`All;()enlist (=;`COMPANY;enlist company)], $[ccy=`All;();enlist (=;`CCY_Pair;enlist ccy)]; ?[`DEALONLINE_REMOVED;wc;0b;`Deal_Time`Deal_Date!`Deal_Time`Deal_Date] } The first part specifies your date range and status = `Completed in the where clause wc:(enlist (within;`Deal_Date;(enlist;startdate;enddate))),(enlist (=;`Status;enlist `Completed)), Next each of these conditionals checks for `All for the TIER, COMPANY and CCY_Pair column filtering. It then joins these on to the where clause when a specific TIER, COMPANY or CCY_Pair are specified. (otherwise an empty list is joined on): $[tier=`All;();enlist (=;`TIER;enlist tier)], $[company=`All;();enlist (=;`COMPANY;enlist company)], $[ccy=`All;();enlist (=;`CCY_Pair;enlist ccy)]; Finally, the select statement is called in its functional form as follows, with wc as the where clause: ?[`DEALONLINE_REMOVED;wc;0b;`Deal_Time`Deal_Date!`Deal_Time`Deal_Date]
oracle: grouping on merged columns
I have a 2 tables FIRST id,rl_no,adm_date,fees 1,123456,14-11-10,100 2,987654,10-11-12,30 3,4343,14-11-17,20 and SECOND id,rollno,fare,type 1,123456,20,bs 5,634452,1000,bs 3,123456,900,bs 4,123456,700,bs My requirement is twofold, 1, i first need to get all columns from both tables with common rl_no. So i used: SELECT a.ID,a.rl_no,a.adm_date,a.fees,b.rollno,b.fare,b.type FROM FIRST a INNER JOIN SECOND b ON a.rl_no = b.rollno The output is like this: id,rl_no,adm_date,fees,rollno,fare,type 1,123456,14-11-10,100,123456,20,bs 1,123456,10-11-12,100,123456,900,bs 1,123456,14-11-17,100,123456,700,bs 2,Next i wanted to get the sum(fare) of those rollno that were common between the 2 tables and also whose fare >= fees from FIRST table group by rollno and id. My query is: SELECT x.ID,x.rl_no,,x.adm_date,x.fees,x.rollno,x.type,sum(x.fare) as "fare" from (SELECT a.ID,a.rl_no,a.adm_date,a.fees,b.rollno,b.fare,b.type FROM FIRST a INNER JOIN SECOND b ON a.rl_no = b.rollno) x, FIRST y WHERE x.rollno = y.rl_no AND x.fare >= y.fees AND x.type IS NOT NULL GROUP BY x.rollno,x.ID ; But this is throwing in exceptions. ORA-00979: not a GROUP BY expression 00979. 00000 - "not a GROUP BY expression" The expected output will be like this: id,rollno,adm_date,fare,type 1,123456,14-11-10,1620,bs So could someone care to show an oracle newbie what i'm doing wrong here?
It looks like there's a couple different problems here; Firstly, you're trying to group by an x.ID column which doesn't exist; it looks like you'll want to add ID to the selected columns in your sub-query. Secondly, when aggregating with GROUP BY, all selected columns need to be either listed in the GROUP BY statement or aggregated. If you're grouping by rollno and ID, what do you want to have happen to all the extra values for adm_date, fees, and type? Are those always going to be the same for each distinct rollno and ID pair? If so, simply add them to the GROUP BY statement, ie, GROUP BY adm_date, fees, type, rollno, ID If not, you'll need to work out exactly how you want to select which one to be output; If you've got output like your example (adding in an ID column here) ID,adm_date,fees,rollno,fare,type 1,14-11-10,100,123456,20,bs 1,10-11-12,100,123456,900,bs 1,14-11-17,100,123456,700,bs Call that result set 'a'. If I run; SELECT a.ID, a.rollno, SUM(a.fare) as total_fare FROM a GROUP BY a.ID, a.rollno Then the result will be a single row; ID,rollno,total_fare 1,123456,1620 So, if you also select the adm_date, fees, and type columns, oracle has no idea what you mean to do with them. You're not using them for grouping, and you're not telling oracle how you want to pick which one to use. You could do something like SELECT a.ID, FIRST(a.adm_date) as first_adm_date, FIRST(a.fees) as first_fees, a.rollno, SUM(a.fare) as total_fare, FIRST(a.type) as first_type FROM a GROUP BY a.ID, a.rollno Which would give the result; ID,first_adm_date,first_fees,rollno,total_fare,first_type 1,14-11-10,100,123456,1620,bs I'm not sure if that's what you mean to do though.
PostgreSQL and pl/pgsql SYNTAX to update fields based on SELECT and FUNCTION (while loop, DISTINCT COUNT)
I have a large database, that I want to do some logic to update new fields. The primary key is id for the table harvard_assignees The LOGIC GOES LIKE THIS Select all of the records based on id For each record (WHILE), if (state is NOT NULL && country is NULL), update country_out = "US" ELSE update country_out=country I see step 1 as a PostgreSQL query and step 2 as a function. Just trying to figure out the easiest way to implement natively with the exact syntax. ==== The second function is a little more interesting, requiring (I believe) DISTINCT: Find all DISTINCT foreign_keys (a bivariate key of pat_type,patent) Count Records that contain that value (e.g., n=3 records have fkey "D","388585") Update those 3 records to identify percent as 1/n (e.g., UPDATE 3 records, set percent = 1/3)
For the first one: UPDATE harvard_assignees SET country_out = (CASE WHEN (state is NOT NULL AND country is NULL) THEN 'US' ELSE country END); At first it had condition "id = ..." but I removed that because I believe you actually want to update all records. And for the second one: UPDATE example_table SET percent = (SELECT 1/cnt FROM (SELECT count(*) AS cnt FROM example_table AS x WHERE x.fn_key_1 = example_table.fn_key_1 AND x.fn_key_2 = example_table.fn_key_2) AS tmp WHERE cnt > 0) That one will be kind of slow though. I'm thinking on a solution based on window functions, you may want to explore those too.