Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sql multiple nested selects

As you can see, the beginning and the end of the week are selected with this code. I’m new to sql and I understand what’s going on here in general, but I can’t explain it in detail. For example,

(select lookupweekid-1 from lookupday where dateoftransaction = date) t2 (lookupweekid)

This one confused me a lot. (…) t2 (…), <-I don’t understand what the parenthesis in the last part is telling

select start_of_week,end_of_week from
(select dateoftransaction
 from lookupday t1,
      (select lookupweekid-1 from lookupday 
       where dateoftransaction = date) t2 (lookupweekid)
 where t1.lookupweekid=t2.lookupweekid
   and t1.weekdaynumber=1) t3 (start_of_week)
,(select dateoftransaction
  from lookupday t1,
       (select lookupweekid-1 from lookupday 
        where dateoftransaction = date) t2 (lookupweekid)
  where t1.lookupweekid=t2.lookupweekid
  and t1.weekdaynumber=7) t4 (end_of_week)
;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

t4 (end_of_week) is a table alias that also defines a column alias. This avoids having to specify the column aliases inside the derived table.

So this:

(select dateoftransaction
 from lookupday t1 ... 
 where t1.lookupweekid=t2.lookupweekid
 and t1.weekdaynumber=7) t4 (end_of_week)

is equivalent to:

(select dateoftransaction as end_of_week
 from lookupday t1 ... 
 where t1.lookupweekid=t2.lookupweekid
 and t1.weekdaynumber=7) t4

This is e.g. explained in the Postgres manual

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading