INNER JOIN DIM TABLE TO FOUND ID OF FIPS - mysql

I am currently trying to query the fips code and sum of the amount of cases for that code from the cases table and the id of the fips code for the subquery from the dim_counties table.
Here's what I have so far that has worked:
SELECT DISTINCT C.FIPS,
SUM(C.CASES) AS SUMS
FROM DIM_DATE_MONTH B, CASES C
where 1=1
and B.DATE_SHORT = SUBSTR(TO_CHAR(C.DAY_OF, 'MONTH'), 1,3)
AND B.DATE_YR = SUBSTR(EXTRACT(YEAR FROM C.DAY_OF),1,4)
AND SUBSTR(TO_CHAR(C.DAY_OF, 'MONTH'), 1,3) = 'JAN'
AND SUBSTR(EXTRACT(YEAR FROM C.DAY_OF),1,4) = '2020'
GROUP BY C.FIPS
ORDER BY SUMS DESC
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY;
What I have attempted that doesn't work
SELECT A.COUNTY_NBR,
A.FIPS,
D.SUMS
FROM DIM_COUNTIES A
INNER JOIN(
SELECT DISTINCT C.FIPS,
SUM(C.CASES) AS SUMS
FROM DIM_DATE_MONTH B, CASES C
where 1=1
and B.DATE_SHORT = SUBSTR(TO_CHAR(C.DAY_OF, 'MONTH'), 1,3)
AND B.DATE_YR = SUBSTR(EXTRACT(YEAR FROM C.DAY_OF),1,4)
AND SUBSTR(TO_CHAR(C.DAY_OF, 'MONTH'), 1,3) = 'JAN'
AND SUBSTR(EXTRACT(YEAR FROM C.DAY_OF),1,4) = '2020'
GROUP BY C.FIPS
ORDER BY SUMS DESC
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY)D ON D.SUM) D ON C.FIPS = A.FIPS;

Related

How can I GROUP BY SELECT subquery aggregates?

first time on here, hoping for help. (MySQL) I tried to use subqueries in a SELECT statement but when I GROUP BY, the single aggregate value outputs of the subqueries just produce the one same value for all rows in the table. This implies they are not GROUPED, right? How close am I to getting this right? Thanks
SELECT
c.name, ca.name, DATE_FORMAT(sp.created,'%Y%m') AS yr_month,
ss.signup_source, count(sp.seller_profile_id) AS No_seller_profiles,
(SELECT SUM(seller_invoice.gbp_value)/100
FROM seller_invoice JOIN seller_profile
ON seller_invoice.seller_profile_id = seller_profile.seller_profile_id
WHERE seller_invoice.created BETWEEN seller_profile.created AND ADDDATE(seller_profile.created, INTERVAL 30 DAY)),
(SELECT count(project_response.project_response_id)
FROM project_response JOIN seller_profile
ON project_response.seller_profile_id = seller_profile.seller_profile_id
WHERE project_response.created BETWEEN seller_profile.created AND ADDDATE(seller_profile.created, INTERVAL 30 DAY) AND project_response.is_visible_to_seller = 1)
FROM seller_profile AS sp
JOIN country AS c ON sp.country_id = c.country_id
JOIN seller_category AS sc ON sp.seller_profile_id = sc.seller_profile_id
JOIN category AS ca ON sc.category_id = ca.category_id
JOIN seller_signup_source AS ss ON sp.seller_profile_id = ss.seller_profile_id
WHERE sp.created BETWEEN '2018-11-01' AND '2018-12-31'
GROUP BY 1,2,3,4;

Get only 1 result per group of ID

I have a list of records (domestic_helper_idcards) and I want to return only one card per staff (domestic_helper_id) that is not deleted (is_deleted = 0), and that has the card_expiration_date furthest in the future (latest expiry date).
Have tried grouping and so on, but cant get it to work. Code below:
SELECT * FROM domestic_helper_idcard
where
is_deleted = 0
order by card_expiration_date desc
This returns the following (image):
I want only records with ID 4 and 5 to be returned. Anyone?
You could use a join with the subquery grouped by domestic_helper_id with an aggregated function eg: max()
SELECT d.*
FROM domestic_helper_idcard d
inner join (
select domestic_helper_id, max(id) max_id
from domestic_helper_idcard
where is_deleted = 0
group by domestic_helper_id
) t on t.domestic_helper_id = d.domestic_helper_id and t.max_id = d.id
order by d.card_expiration_date desc
and as suggested by Jens after clarification using max card_expiration_date
SELECT d.*
FROM domestic_helper_idcard d
inner join (
select domestic_helper_id, max(card_expiration_date) max_date
from domestic_helper_idcard
where is_deleted = 0
group by domestic_helper_id
) t on t.domestic_helper_id = d.domestic_helper_id and t.max_date = d.max_date
order by d.card_expiration_date desc

Sorting SQL results in the query

I have a query like this:
SELECT A.*,
B.surname,
B.name,
C.url_address,
(SELECT Concat(file_path, '/', file_name) AS image
FROM psuploadedfiles B
WHERE enum = 3
AND category = A.id_user
ORDER BY number ASC
LIMIT 1) AS image2,
(SELECT Concat(file_path, '/', file_name) AS image
FROM psuploadedfiles B
WHERE enum = 3
AND category = A.post_id
ORDER BY number ASC
LIMIT 1) AS image
FROM psposts A
LEFT JOIN psuserdetails B
ON B.id_user = A.id_user
LEFT JOIN psuser C
ON C.id_user = A.id_user
WHERE A.enable = '1'
AND ( A.id_user = 21
OR ( A.id_user = '7'
OR A.id_user = '1'
OR A.id_user = '5' ) )
ORDER BY date DESC
LIMIT 0, 25;
In the psPosts table, I have a subscriptions_date column (containing a date in yyyy-mm-dd format) where subscriptions_date is date until when the post will be promoted.
How can I sort the results in such a way that there are posts at the top containing subscriptions_date current or future date (i.e. promoted), and underneath the other posts?
Something like...
ORDER BY
CASE WHEN A.subscriptions_date >= NOW() THEN 0 ELSE 1 END,
date
The first sort criteria splits data into two groups, with current or future subscriptions in first place. Within each group, data is then sorted by date.

Join between sub-queries in SQLAlchemy

In relation to the answer I accepted for this post, SQL Group By and Limit issue, I need to figure out how to create that query using SQLAlchemy. For reference, the query I need to run is:
SELECT t.id, t.creation_time, c.id, c.creation_time
FROM (SELECT id, creation_time
FROM thread
ORDER BY creation_time DESC
LIMIT 5
) t
LEFT OUTER JOIN comment c ON c.thread_id = t.id
WHERE 3 >= (SELECT COUNT(1)
FROM comment c2
WHERE c.thread_id = c2.thread_id
AND c.creation_time <= c2.creation_time
)
I have the first half of the query, but I am struggling with the syntax for the WHERE clause and how to combine it with the JOIN. Any one have any suggestions?
Thanks!
EDIT: First attempt seems to mess up around the .filter() call:
c = aliased(Comment)
c2 = aliased(Comment)
subq = db.session.query(Thread.id).filter_by(topic_id=122098).order_by(Thread.creation_time.desc()).limit(2).offset(2).subquery('t')
subq2 = db.session.query(func.count(1).label("count")).filter(c.id==c2.id).subquery('z')
q = db.session.query(subq.c.id, c.id).outerjoin(c, c.thread_id==subq.c.id).filter(3 >= subq2.c.count)
this generates the following SQL:
SELECT t.id AS t_id, comment_1.id AS comment_1_id
FROM (SELECT count(1) AS count
FROM comment AS comment_1, comment AS comment_2
WHERE comment_1.id = comment_2.id) AS z, (SELECT thread.id AS id
FROM thread
WHERE thread.topic_id = :topic_id ORDER BY thread.creation_time DESC
LIMIT 2 OFFSET 2) AS t LEFT OUTER JOIN comment AS comment_1 ON comment_1.thread_id = t.id
WHERE z.count <= 3
Notice the sub-query ordering is incorrect, and subq2 somehow is selecting from comment twice. Manually fixing that gives the right results, I am just unsure of how to get SQLAlchemy to get it right.
Try this:
c = db.aliased(Comment, name='c')
c2 = db.aliased(Comment, name='c2')
sq = (db.session
.query(Thread.id, Thread.creation_time)
.order_by(Thread.creation_time.desc())
.limit(5)
).subquery(name='t')
sq2 = (
db.session.query(db.func.count(1))
.select_from(c2)
.filter(c.thread_id == c2.thread_id)
.filter(c.creation_time <= c2.creation_time)
.correlate(c)
.as_scalar()
)
q = (db.session
.query(
sq.c.id, sq.c.creation_time,
c.id, c.creation_time,
)
.outerjoin(c, c.thread_id == sq.c.id)
.filter(3 >= sq2)
)

MySql sort by highest value with inner join and subquery

I have a query that has a sub query that returns a count of records from another table, I'm having trouble ordernar the largest number of this counter
SELECT respostas.id,
respostas.cmm,
respostas.topico,
respostas.usuario,
respostas.resposta,
perfis.nome,
perfis.sobrenome,
respostas.datahora,
(
SELECT count(id)
FROM likes
WHERE respostas.id = resposta
) AS total
FROM respostas
INNER JOIN perfis ON respostas.usuario = perfis.id
INNER JOIN likes ON respostas.topico = likes.topico
WHERE respostas.cmm = 28
AND respostas.topico = 38
ORDER BY respostas.id ASC, total ASC
LIMIT 0,20`enter code here`
I want to sort by the total column and can not.
Sorting by total does not work, only ordered by id
You can choose which column to order by numerically:
SELECT
(
SELECT count(id)
FROM likes
WHERE respostas.id = resposta
) AS total,
respostas.id,
respostas.cmm,
respostas.topico,
respostas.usuario,
respostas.resposta,
perfis.nome,
perfis.sobrenome,
respostas.datahora
FROM respostas
INNER JOIN perfis ON respostas.usuario = perfis.id
INNER JOIN likes ON respostas.topico = likes.topico
WHERE respostas.cmm = 28
AND respostas.topico = 38
ORDER BY 1, respostas.id
LIMIT 0,20
What is the purpose of Order By 1 in SQL select statement?