First... i have a SQLite database:
I have an user table tbl_members
member_id
name
and an order table tbl_orders
order_id
member_ids
name
An order can be edited by more than one member and this members are stored in tbl_orders member_ids in this fashion 1,2,34,23,65,
I need a query that returns:
tbl_members.member_id, tbl_members.name and a COUNT(tbl_orders.order_id) of the orders where the tbl.members.member_id is in tbl.orders.member_ids
I can't get it... can anyone give me a hint?
is this your expected answer?
SELECT tm.member_id, tm.name, COUNT(to.order_id)
FROM tbl_members as tm
LEFT JOIN tbl_orders as to on tm.member_id = to.member_id
GROUP BY tm.member.id, tm.name
I got it!
SELECT tm.member_id, tm.name, COUNT(to.order_id)
FROM tbl_members tm
LEFT JOIN tbl_orders to ON (to.member_ids LIKE '%,'||tm.member_id||'%')
GROUP BY tm.member_id
Works for me
Related
I have been trying to write the SQLAlchemy code that should function as the following SQL query.
SELECT * FROM events AS ev
INNER JOIN event_types AS et1 on ev.event_type_id = et1.id
INNER JOIN (
SELECT event_type, MAX(created_at) AS LatestCreatedAt
FROM event_types et GROUP BY event_type
) AS et2
ON
et2.event_type = et1.event_type
AND
et2.LatestCreatedAt = et1.created_at
What I'm trying to do is to
Get all columns from the events table
Inner join the event_type table (et1) on the event table
Group by the event_type with only the rows that have the latest record (i.e. Filter out old event types by looking at created_at if duplicated)
Inner join the grouped event_type (et2) on the event_type table (et1)
What I wrote for the SQL Alchemy version of the above is
from sqlalchemy import func
subquery = session.query(EventTypeTable.event_type,
func.max(EventTypeTable.created_at).group_by(EventTypeTable.event_type)).all()
events = (session.query(EventTable)
.join(EventTypeTable)
.join(subquery)
.all())
However, I get the following error.
Neither 'max' object nor 'Comparator' object has an attribute 'group_by'
It seems to complain that I can not use group_by with max function. Is there any other way to get the query results while leaving only the latest record on the created_at column in the event_type table in SQL Alchemy?
Any help or comments are appreciated. Thank you!
I want to change this raw SQL to Django ORM but I couldn't manage to convert.
most_read_students = LendedBook.objects.raw('
SELECT student_id as id, name, surname, COUNT(*) as count
FROM "Book_lendedbook"
INNER JOIN User_student on Book_lendedbook.student_id=User_student.id
where did_read=1
group by student_id
order by count DESC
LIMIT 5')`
I tried this and I get close result.But unfortunately, I couldn't do what I want. Because I want to join this table with another table.
most_read_students = LendedBook.objects.values('student_id')
.filter(did_read=True, return_date__month=(datetime.datetime.now().month))
.annotate(count=Count('student_id'))
When I use select_related with "User_student" table like this;
most_read_students = LendedBook.objects.select_related('User_student')
.values('student_id', 'name', 'surname')
.filter(did_read=True, return_date__month=(datetime.datetime.now().month))
.annotate(count=Count('student_id'))
It throws an error like Cannot resolve keyword 'name' into field. Choices are: book, book_id, did_read, id, is_returned, lend_date, return_date, student, student_id
But I should be able to get student properties like name and surname when I join "User_student" table.
Thank you for your help!
I solved it!
How to combine select_related() and value()? (2016)
Funny fact; my problem was not about ORM i guess. I didn't know I could reach student object's properties by just adding this to .values('student__name', 'student__surname') in the last code I've shared on this post.
This code ;
LendedBook.objects.select_related('User_student')
.values('student_id', 'name', 'surname')
.filter(did_read=True, return_date__month=(datetime.datetime.now().month))
.annotate(count=Count('student_id'))
To this code ;
LendedBook.objects.select_related('User_student')
.values('student_id', 'student__name', 'student__surname')
.filter(did_read=True, return_date__month=(datetime.datetime.now().month))
.annotate(count=Count('student_id'))
By the way, deleting .select_related('User_student') doesn't affect the result.
So, using _ _ solved my problem!
Hello I need help with Python and SQL.
I have 2 tables:
users_table:
userid | name |
tasks_table:
userid | name | date
What I need it's get users ids from 1st table:
SELECT userid FROM users_table
And use those userids to make SELECT from second table:
SELECT count(date) from tasks_table WHERE userid=xxx
How can I do it with python? I'm tried to use loop but it didn't work for some reason maybe I did something wrong.
I'll be grateful for any help.
Thanks!
SELECT U.USER_ID,COUNT(T.DATE)AS CNT
FROM USERS_TABLE AS U
LEFT JOIN TASKS_TABLE AS T ON U.USER_ID=T.USER_ID
GROUP BY U.USER_ID
I'm try to filter if id of column A not exist in column B by this code.
query = db.session.query().select_from(Spare_Parts, Vendors, Replacement)\
.filter(Vendors.vendor_code == Spare_Parts.vendor_code,\
~ exists().where(Spare_Parts.spare_part_code == Replacement.spare_part_code))
I want to query the data from Spare_Parts that not have an id exist in Replacement as a foriegn key but i got the error like this.
Select statement 'SELECT *
FROM spare_parts, replacement
WHERE spare_parts.spare_part_code = replacement.spare_part_code' returned no FROM clauses due to auto-correlation; specify correlate(<tables>) to control correlation manually.
So what is a problem and how to fix that.
try to use the subquery like this instead
to filter spare_part_code from spare_parts which are not in replacement table``
SELECT *
FROM spare_parts
WHERE spare_parts.spare_part_code not in
(select distinct
replacement.spare_part_code
FROM replacement)
or you can use not exists
SELECT *
FROM spare_parts
WHERE not exists
(select 1
FROM replacement
where spare_parts.spare_parts_code = replacement.spare_parts_code)
If I have a SQL script is there a way to parse and extract the columns and tables referenced in the script into a table like structure :
Script:
Select t1.first, t1.last, t2.car, t2.make, t2.year
from owners t1
left join cars t2
on t1.owner_id = t2.owner_id
Output:
Table Column
owners first
owners last
owners owner_id
cars car
cars make
cars year
cars owner_id
Old question but interesting so here it goes - turn your script temporarily into a stored procedure forcing SQL Server to map the dependencies and then you can retrieve them by using:
SELECT referenced_entity_name ,referenced_minor_name FROM sys.dm_sql_referenced_entities('dbo.stp_ObjectsToTrack', 'Object')
This is what you want in SQL Server:
select t.name as [Table], c.name as [Column]
from sys.columns c
inner join sys.tables t
on c.object_id = t.object_id