Question

I am new to this game and have spent some time trying to learn the basics. However, my limited SQL knowledge fails me in attempting to build a slightly complex query. I shall now try to explain (Help is much appreciated).

I have two tables which are setup as follows

Table 1

 PrjName  | StartDate|  MidDate  |  EndDate

 -----------------------------------------
    abc   | 01/01/2014| 11/03/2014| 06/05/2014

    def   | 21/03/2014| 19/05/2014| 16/11/2014

    ghi   | 15/07/2014| 20/10/2014| 20/12/2014

   jkl    | 04/02/2014| 09/06/2014| 30/09/2014

Table 2

 PrjName |   Phase   |  Outcome

 -----------------------------------------
   abc   | StartDate | Green 

   ghi   | MidDate   | Yellow

   def   | EndDate   | Green 

   jkl   | StartDate | Red

The query which I want to create should meet the following conditions:

  • If current date is within certain range in table 1 THEN return the column name and PrjName e.g. current date = 05/10/2014 --> would return "ghi & MidDate" and "def & EndDate"
  • The Results from this query would then be used in a subquery to find the corresponding Outcome counts e.g. Using the previous conditions ---> would return " 1 count Yellow & 1 count Green" These subquery output would also be grouped by both "Phase" and by "Outcome" so the output table would look something like this:

Table 3

 Phase      | Outcome |  Count

 ------------------------------
  MidDate   | Green   |  1

  EndDate   | Yellow  |  1

Obviously the tables would contain several more "Phases" and much more "Outcomes" but the general principle is the same.

I can get Table 3 quite easily, but not using the conditions which would be derived from the table 1 i.e. the FieldName (e.g. MidDate) and the PrjName.

Was it helpful?

Solution

Your question is not clear about what you are counting. Is it Phase or OutCome? Anyway, I've assumed that you are counting Phase and wrote these queries. Those are checked and confirmed with SQL Server 2008.

Query1

SELECT t2.PrjName,t2.Phase,t2.OutCome
FROM Table1 t1
Inner Join 
Table2 t2
ON t1.PrjName = t2.PrjName
Where t1.StartDate <= GETDATE()
AND t1.EndDate >= GETDATE()

Query2

SELECT t2.Phase,t2.OutCome, COUNT(t2.OutCome)as [Count]
FROM Table1 t1
Inner Join 
Table2 t2
ON t1.PrjName = t2.PrjName
Where t1.StartDate <= GETDATE()
AND t1.EndDate >= GETDATE()
Group by t2.Phase,t2.OutCome
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top