简体   繁体   中英

get SQL results of a query

I've a sample headquarter table

id     name         
1      California   
2      Florida City
3      Washington DC
4      Oklahoma

Also I've a sample Sales data table

id     headquarter_id     Sales       Year
 1          2             2000        2021
 2          3             5000        2021
 3          4             1000        2021

My SQL query is

select hq.name, st.Year, st.sales from salesTable st
left join headquarters hq on hq.id = st.headquarter_id

The results are

name              Year      Sales
Florida City      2021      2000
Washington DC     2021      5000
Oklahoma          2021      1000

Is there any possibility to get the results like below even though there is no sales record of California in sales table?

name              Year      Sales
California        2021      0
Florida City      2021      2000
Washington DC     2021      5000
Oklahoma          2021      1000

It seems that you're not getting the result because of the left join. The way you did, it will not match California since it has no data on Sales data table.

Try this one:

select 
hq.name,
 st.Year,
case when st.sales is null then 0 else st.sales end as sales
from headquarters hq
left join salesTable st on hq.id = st.headquarter_id

@Guilherme Barbosa gave you correct query but let me explain the reason behind it.

LEFT JOIN : It select all records of source/root table on your left and select matching records on right side table. Even if matching records not found on right table it'll display all records of left side table.

Follow top to bottom table sequence in JOIN as follow. t1 is coming first so its on left side of query in ON t1.id = t2.id and t2 comes before t3 so ON t2.id = t3.id

SELECT *****
FROM table1 t1
LEFT JOIN table3 t2
**ON t1.id = t2.id**
LEFT JOIN table3 t3
**ON t2.id = t3.id**

Now in your query you are using salesTable as source/root table in your query which has only 3 headquarter_id and its on left side (LEFT JOIN) of your data selection query. Thus it returns only 3 records.

If you use source/root table headquarter in FROM clause then its going to select all your headquarter and display records matching in salesTable .

Correct query is as follow.

SELECT hq.name, st.Year,
    CASE
        WHEN st.sales IS NULL THEN 0
        ELSE st.sales
    END AS sales
FROM headquarters hq
LEFT JOIN salesTable st ON
hq.id = st.headquarter_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM