Is it possible to perform a dynamic SQL join?

What am I doing wrong with this SQL join?

  • SELECT PERIOD_TABLE.BUS_DATE, STORE_MASTER.STORE_NO, SALES.NET_SALES_AMT FROM PERIOD_TABLE LEFT OUTER JOIN SALES ON PERIOD_TABLE.BUS_DATE=SALES.BUS_DATE LEFT OUTER JOIN STORE_MASTER ON SALES.STORE_NO=STORE_MASTER.STORE_NO ORDER BY STORE_MASTER.STORE_NO, PERIOD_TABLE.BUS_DATE I am trying to get a record for every day and every store whether or not it has sales. My period table contains a record for every day from 1990-2020 and my store master has a record for every store. I want the results to look something like this: Date-----------Store---Sales 01/01/1990 001466 Null... 01/02/1990 001466 149.50 01/03/1990 001466 200.34 ... I am getting one record for each day within the period table whether or not there is a record in my sales table for that day, but the store is showing up null too. Like this: Date-----------Store---Sales 01/01/1990 Null... Null... 01/02/1990 001466 149.50 01/03/1990 001466 200.34 ... How should I modify this to get one record per store per day?

  • Answer:

    "LEFT OUTER JOIN STORE_MASTER ON SALES.STORE_NO=STORE_MASTER.STORE_NO" No store will be found when no sale is found. SELECT PERIOD_TABLE.BUS_DATE, STORE_MASTER.STORE_NO, SALES.NET_SALES_AMT FROM STORE_MASTER LEFT OUTER JOIN PERIOD_TABLE ON 1 = 1 LEFT OUTER JOIN SALES ON PERIOD_TABLE.BUS_DATE=SALES.BUS_DATE AND SALES.STORE_NO=STORE_MASTER.STORE_NO ORDER BY STORE_MASTER.STORE_NO, PERIOD_TABLE.BUS_DATE

Matt W at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

I think the solution is to use RIGHT OUTER JOIN for the STORE_MASTER. The left version is guaranteeing all the SALES.STORE_NO's are in the table some of which are null from the previous join. You want all the STORE_MASTER.STORE_NO's in the table. The other way wold be to outer join period_table and store_master without criteria (all periods mixed with all stores) and then join sales.

Rick B

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.