0

I have been working with SQL joins and kinda stuck with following scenario:

Table 1: PK(ID, GRADE)

| ID | Grade | Student_Count |

|   1   |     10th     |               20                  |
|   1   |     9th       |               20                  |
|   2   |     10th     |               20                  |
|   2   |       9th     |               20                  |


Table 2:PK(ID, Grade, Visited_Date)

| ID | Grade | Visited | Visit_Date |

|   1   |    10th     |      Yes       |  25-Dec-2015  |
|   1   |    10th     |       No        |  26-Dec-2015  |
|   1   |     9th      |      Yes       |  28-Dec-2015  |
|   1   |     9th      |       No        |  29-Dec-2015  |
|   2   |    10th     |      Yes       |  27-Dec-2015  |
|   2   |     9th      |       No        |  30-Dec-2015  |


What i need is a SELECT query which returns data from both the tables for a given ID in such a way that output rows should match the data of the Table 2 (no all possible combinations like cross/dot product) along with non-common columns from Table 1.

For example for ID "1" the output should be:

| ID | Grade | Student_Count | Visited | Visit_date |

|   1   |     10th     |               20                  |      Yes      |  25-Dec-2015  |

|   1   |     10th     |               20                  |       No       |  26-Dec-2015  |

|   1   |      9th      |               20                  |      Yes      |  28-Dec-2015  |

|   1   |      9th      |               20                  |       No       |  29-Dec-2015  |

Note: There is no foreign key association between both the tables.

Prashant soni
  • 85
  • 1
  • 8

1 Answers1

0

You have to JOIN both tables on the id and grade fields.

SELECT b.ID, b.Grade, a.Student_Count, b.Visited, b.Visit_date
FROM table2 b 
INNER JOIN table1 a 
ON a.ID = b.ID AND a.Grade = b.Grade
ORDER BY a.ID
antoniodvr
  • 1,259
  • 1
  • 14
  • 15