I am tying to ordering a sub query before grouping it. The problem is that the sub query is order as if we take it just like a query. But as sub query order by does nothing.
Here's the query:
SELECT * FROM (
SELECT
a.id,
citypair,
a.season,
airline,
class,
fare,
rbd,
season_from,
season_to,
schedule_id,
cp.departure_id,
cp.destination_id,
sch.date_time
FROM tarifftool_price_log as a
JOIN tarifftool_seasons as b ON a.seasonId = b.id
JOIN tarifftool_citypairs as cp ON citypair = cp.id
JOIN tarifftool_schedule_queue AS sch ON schedule_id = sch.id
WHERE b.date = '12/26' AND class = 'b' ORDER BY schedule_id DESC) as qq
GROUP BY citypair, airline
Now i'am just trying as a result get a ordered query. If I do achieve this, i will have no problem grouping my data.
Use Row_Number in sub query
ROW_NUMBER() OVER(ORDER BY schedule_id)
SELECT * FROM (
SELECT
ROW_NUMBER() OVER(ORDER BY schedule_id DESC ) as RowId,
a.id,
citypair,
a.season,
airline,
class,
fare,
rbd,
season_from,
season_to,
schedule_id,
cp.departure_id,
cp.destination_id,
sch.date_time
FROM tarifftool_price_log as a
JOIN tarifftool_seasons as b ON a.seasonId = b.id
JOIN tarifftool_citypairs as cp ON citypair = cp.id
JOIN tarifftool_schedule_queue AS sch ON schedule_id = sch.id
WHERE b.date = '12/26' AND class = 'b' ) as qq
GROUP BY citypair, airline
Related
hi i need help combining 2 cte to get who get 100 attendance percentage but failed at exam
here my first cte
with main as(
select ca.STUDENT_ID,
ca.SCHEDULE_ID,
s.COURSE_ID,
co.NAME as course_name,
st.NAME,
count(ca.ID) as total_attendance,
((CHAR_LENGTH(s.COURSE_DAYS) - CHAR_LENGTH(REPLACE(s.COURSE_DAYS , ',', '')) + 1) * 13) as attendance_needed
from univ.course_attendance ca
left join univ.schedule s on ca.SCHEDULE_ID = s.ID
left join univ.student st on ca.SCHEDULE_ID = st.ID
left join univ.course co on ca.SCHEDULE_ID = co.ID
group by ca.STUDENT_ID, ca.SCHEDULE_ID
)
select *,total_attendance/attendance_needed as attendance_percentage
from main
order by 1,2;
second cte
;with inputdata as
(
select es.STUDENT_ID,es.EXAM_ID,es.SCORE,e.PASS_THRESHOLD, s.NAME , c.NAME as Course_name, es.EXAM_DT,
case
when SCORE>=PASS_THRESHOLD then 'PASS'
else 'Fail'
end as Flag
from exam_submission es
left join student s on es.STUDENT_ID = s.ID
left join exam e on es.EXAM_ID = e.ID
left join course c on e.COURSE_ID = c.ID
)
select * from inputdata I
join
( select student_id,exam_id from
inputdata
group by student_id, exam_id
)T on I.student_id=T.student_id and I.exam_id=T.exam_id
order by exam_dt asc
result:
what i need student name, course name, attendace percentage & flag "failed/pass"
Just chain multiple table expressions in a single CTE by introducing "aliases" like main_ordered for the first CTE and inputdata_grouped for the second one. I'm sticking with the original naming, but it could be improved.
with
main as (
select ca.STUDENT_ID,
...
group by ca.STUDENT_ID, ca.SCHEDULE_ID),
main_ordered as (
select *,total_attendance/attendance_needed as attendance_percentage
...
order by 1,2),
inputdata as (
select es.STUDENT_ID,es.EXAM_ID,es.S...
...),
inputdata_grouped as (
select * from inputdata I
...
group by student_id, exam_id...
...
order by exam_dt asc)
select *
from main_ordered join inputdata_grouped on ...
SELECT p.ID, Name
FROM Policies p
INNER JOIN ProgramYears py ON p.ProgramYearID = py.id
INNER JOIN (SELECT MemberID, max(EffectiveDate) AS EffectiveDate
FROM Policies
GROUP BY MemberID) TEMP
ON p.memberid = TEMP.MemberID
AND p.EffectiveDate = TEMP.effectivedate
AND p.memberid NOT IN (SELECT MemberID
FROM InvoiceDetail
WHERE ProgramYear = NAME)
NOT EXISTS is usually a better substitute for NOT IN, but your choices largely depend on the data and the structure of your tables and indexes.
Try the query below, but compare its execution plan to that of your current query; what works for one scenario may not work for another.
SELECT p.ID, Name
FROM Policies p
INNER JOIN ProgramYears py ON p.ProgramYearID = py.id
INNER JOIN (SELECT MemberID, max(EffectiveDate) AS EffectiveDate
FROM Policies
GROUP BY MemberID) TEMP
ON p.memberid = TEMP.MemberID
AND p.EffectiveDate = TEMP.effectivedate
WHERE NOT EXISTS
(SELECT MemberID
FROM InvoiceDetail AS ID
WHERE ID.ProgramYear = NAME
AND p.MemberId = ID.MemberId)
You can try:
SELECT a.ID, a.Name
FROM (SELECT p.ID, Name,
ROW_NUMBER()OVER(PARTITION BY p.memberid ORDER BY p.EffectiveDate DESC) AS rnk
FROM Policies p
INNER JOIN ProgramYears py ON p.ProgramYearID = py.id
WHERE NOT EXISTS (SELECT MemberID
FROM InvoiceDetail AS ID
WHERE ID.ProgramYear = NAME
AND p.MemberId = ID.MemberId)
) a
WHERE a.rnk = 1
I wrote the following query to return the the records with the latest date.
select fs.company_id, max(fs.create_dt) as latestcreatedate
from field_sale fs
group by fs.company_id
order by fs.company_id
The query all works fine. But I need to retrieve the record with all related columns attached to it. Such as, id, title, desc and etc.
How can I retrieve the records with its corresponding columns?
Couple ways of doing so :
-- 1.
SELECT a.*
FROM field_sale a
INNER JOIN
(
select fs.company_id, max(fs.create_dt) as latestcreatedate
from field_sale fs
group by fs.company_id
)b
ON b.company_id = a.company_id AND b.latestcreatedate = a.create_dt
order by a.company_id;
-- 2.
SELECT b.* FROM
(
SELECT a.* , ROW_NUMBER()
OVER (PARTITION BY a.company_id ORDER BY a.create_dt DESC)
AS rn
FROM field_sale a
)b WHERE b.rn = 1
ORDER BY company_id
WITH t AS (
SELECT fs.company_id,
fs.create_dt AS latestcreatedate,
id,
title,
etc,
ROW_NUMBER() OVER ( PARTITION BY fs.company_id ORDER BY fs.create_dt DESC ) AS rowNum
FROM field_sale fs
)
SELECT t.company_id,
t.latestcreatedate,
t.id,
t.title,
t.etc
FROM t
WHERE t.rowNum = 1
ORDER BY t.company_id
I'm breaking my head trying to modify this query(thx sgeddes) in order to
get at result not only from db_events.events fields, instead join it with some db_system.devices fields
SELECT e.*
FROM db_events.events e
JOIN (
SELECT Max(id) MaxId, device_id
FROM db_events.events
GROUP BY device_id ) e2 on e.Id = e2.MaxId AND e.device_id = e2.device_id
WHERE e.device_id IN (
SELECT device_id
FROM db_system.devices
WHERE vendor = 1)
ORDER BY e.id DESC
How can I get it without repeat the subquery:
SELECT *
FROM db_system.devices
WHERE vendor = 1
I need get db_system.devices.brand and db_system.devices.model joined with final results, and
I tried to modify it step to step, I tried with temporary tables, I suspect it should be something simple, but I have not been able to do it, of course thank you very much...
is this what you want?
SELECT e.*, a.*
FROM db_events.events e
INNER JOIN
(
SELECT Max(id) MaxId, device_id
FROM db_events.events
GROUP BY device_id
) e2 on e.Id = e2.MaxId AND
e.device_id = e2.device_id
INNER JOIN db_system.devices a
ON e.device_id = a.device_id AND
a.vendor = 1
ORDER BY e.id DESC
the condition a.vendor = 1 can also be moved on WHERE clause and the result is still the same since you are using INNER JOIN
SELECT ....
FROM .... JOIN ....
WHERE a.vendor = 1
ORDER BY ...
I have a table called Request.
Other tables are linked to the Request table through a request id.
There is a TwitterTweet table and a FacebookPost table.
So a single request can have 50 TwitterTweets and/or 20 FacebookPosts or any amount of Tweets/Posts
We can add them together for a total count of 70.
I'm trying to create a query that could tell me what is the request with the highest total count.
I know this is wrong:
(I attempted to just order them by the counts within the TwitterTweet, but it would not let me do an OUTER JOIN which I thought
would bring back the Count.count column. It forced me to do a Left Join for it to compile. My Logic was to do a join so
that the results were calculated for each row by the requestid)
SELECT r1.`id` AS requestid, r1 . *
FROM `Request` AS r1
LEFT JOIN
(SELECT COUNT( * ) AS count, rid
FROM
((SELECT `TwitterTweet`.`id` AS `smid` , `TwitterTweet`.`requestid` AS rid
FROM `TwitterTweet`
WHERE `TwitterTweet`.`requestid` = requestid
AND `TwitterTweet`.`active` =1) AS talias
)) AS Count ON ( Count.rid = requestid )
ORDER BY Count.count
*When I tried to add in the Facebook side it would not compile any more
(The concept is that the results are added from TwitterTweet with the results from FacebookPost
that are attached to the specific requestid which would give us a count. The entire result
set should be ordered by that count)
SELECT r1.`id` AS requestid, r1 . *
FROM `Request` AS r1
LEFT JOIN
(SELECT COUNT( * ) AS count, rid
FROM
((SELECT `TwitterTweet`.`id` AS `smid` , `TwitterTweet`.`requestid` AS rid
FROM `TwitterTweet`
WHERE `TwitterTweet`.`requestid` = requestid
AND `TwitterTweet`.`active` =1 ) AS talias
UNION All
(SELECT `FacebookPost`.`id` AS `smid`, `FacebookPost`.`requestid` AS rid
FROM `FacebookPost`
WHERE `FacebookPost`.`requestid` = requestid
AND `FacebookPost`.`active` = 1) as falias
)) AS Count ON ( Count.rid = requestid )
ORDER BY Count.count
I updated the Query with an attempt to add an alias:
SELECT rid, SUM(count) total_count
FROM
(
(SELECT COUNT(*) AS count, r.rid
FROM request r
JOIN TwitterTweet tt
ON r.id = tt.requestid
WHERE tt.active = 1
GROUP BY r.rid) AS twitter
UNION ALL
(SELECT COUNT(*) AS count, r.rid
FROM request r
JOIN FacebookPost fp
ON r.id = fp.requestid
WHERE fp.active = 1
GROUP BY r.rid ) AS fbook
)
GROUP BY rid
ORDER BY SUM(count) DESC
I made another adjustment to give the middle subquery an alias, but now I only get one row returned with a zero in the rid column and 5686 in the total_count column...the 5686 might be all of the results.
SELECT counts.rid, SUM(count) total_count
FROM
(
SELECT COUNT(*) AS count, r.requestid AS rid
FROM request r
JOIN TwitterTweet tt
ON r.id = tt.requestid
WHERE tt.active = 1
GROUP BY r.requestid
UNION ALL
SELECT COUNT(*) AS count, r.requestid AS rid
FROM request r
JOIN FacebookPost fp
ON r.id = fp.requestid
WHERE fp.active = 1
GROUP BY r.requestid
) AS counts
GROUP BY counts.rid
ORDER BY SUM(count) DESC
Got it!!!
Thanks for your help guys, I had to remove those joins on the request:
SELECT counts.rid, SUM(count) total_count
FROM
(
SELECT COUNT(*) AS count, tt.requestid AS rid
FROM TwitterTweet tt
WHERE tt.active = 1
GROUP BY tt.requestid
UNION ALL
SELECT COUNT(*) AS count, fp.requestid AS rid
FROM FacebookPost fp
WHERE fp.active = 1
GROUP BY fp.requestid
) AS counts
GROUP BY counts.rid
ORDER BY SUM(count) DESC
SELECT id, SUM(count) total_count
FROM
(
SELECT COUNT(*) AS count, r.id
FROM request r
JOIN TwitterTweet tt
ON r.id = tt.requestid
WHERE tt.active = 1
GROUP BY r.id
UNION ALL
SELECT COUNT(*) AS count, r.id
FROM request r
JOIN FacebookPost fp
ON r.id = fp.requestid
WHERE fp.active = 1
GROUP BY r.id
) sub
GROUP BY id
ORDER BY SUM(count) DESC
;