2014-02-26 4 views
6

저는 비교적 SQL에 익숙하지 않습니다. 그리고 나는 단 하나의 행을 반환하는 아주 간단한 쿼리를 작성하기 위해 힘들게 노력했습니다.SQL의 기간별로 여러 테이블을 조인하는 방법은 무엇입니까?

여러 개의 다른 표에서 여러 개의 값을 선택하려고합니다. 동일한 기간에 대해 각 개수를 가져옵니다. 내 데이터베이스에

테이블이 유사합니다

| CreationDate  | LastName | EventType | 
|:--------------------|------------:|:------------:| ... 
| 2013-01-02 18:00:21 | Doe   |  2  | 
| 2013-01-07 18:00:24 | Blanks  |  2  | ... 
| 2013-01-09 17:00:21 | Puccini  |  1  | 

모든 테이블은 유사한에서 CreationDate 열 수 있습니다.

내 쿼리는 지금 아래와 같은 단일 조인입니다 (작동하는 것처럼 보입니다). 하나 또는 여러 개의 JOIN을 추가하여 단일 행 결과에 테이블 당 여러 개의 계산을 반환 할 수 있습니다. 현재 검색어 :

DECLARE @startdate DATETIME = '##startdate##'; 
DECLARE @enddate DATETIME = '##enddate##'; 

SELECT ISNULL(t2.Year, t1.Year) , 
     ISNULL(t2.Month, t1.Month) , 
     t1.LastName1 , 
     t2.LastName2 
FROM (SELECT DATEPART(year, table1.CreationDate) Year , 
        DATEPART(month, table1.CreationDate) Month , 
        COUNT(table1.column2) LastName1 
      FROM  table1 
      WHERE  EventType = 2 
        AND CreationDate BETWEEN @startdate AND @enddate 
      GROUP BY DATEPART(year, table1.CreationDate) , 
        DATEPART(month, table1.CreationDate) 
     ) AS t1 

     JOIN 

      (SELECT DATEPART(year, table2.CreationDate) Year , 
         DATEPART(month, table2.CreationDate) Month , 
         COUNT(table2.column2) LastName2 
       FROM  table2 
       WHERE EventType = 1 
         AND CreationDate BETWEEN @startdate AND @enddate 
       GROUP BY DATEPART(year, table2.CreationDate) , 
         DATEPART(month, table2.CreationDate) 
      ) AS t2 ON t1.Year = t2.Year 
         AND t1.Month = t2.Month 
ORDER BY t1.Year , 
     t1.Month 

더 많은 JOIN을 추가 할 수 있습니까? (나는 이것을 시도하고 비틀 거렸다.) 또는 각 선택된 열 내에서 지정된 날짜 범위에있는 COUNT (값) 만 반환하는 다른 방법이있다.

도움을 주시면 감사하겠습니다.

+1

시도한 검색어와 표의 데이터 샘플을 Google에 알려주십시오. – wruckie

+0

@wruckie - 코드 샘플 + 데이터베이스 스키마가 추가되었습니다. 더 좋아? – samthebrand

답변

7
DECLARE @startdate DATETIME 
set @startdate= '2013-01-02 18:00:21.000'; 
DECLARE @enddate DATETIME 
set @enddate= '2013-01-09 17:00:21.000'; 


SELECT YEAR , 
     MONTH , 
     [1] , 
     [2] 
FROM ((SELECT DATEPART(year, CreationDate) Year , 
        DATEPART(month, CreationDate) Month , 
        eventType , 
        COUNT(LastName) namecount 
      FROM  table1 
      WHERE  CreationDate BETWEEN @startdate AND @enddate 
      GROUP BY DATEPART(year, CreationDate) , 
        DATEPART(month, CreationDate) , 
        EventType) 
        union all 
      (SELECT DATEPART(year, CreationDate) Year , 
        DATEPART(month, CreationDate) Month , 
        eventType , 
        COUNT(LastName) namecount 
      FROM  table2 
      WHERE  CreationDate BETWEEN @startdate AND @enddate 
      GROUP BY DATEPART(year, CreationDate) , 
        DATEPART(month, CreationDate) , 
        EventType)   
     ) u PIVOT(SUM(namecount) FOR eventtype IN ([1], [2])) as pvt 
ORDER BY Year , 
     Month 

당신은 단지로 추가, 더 EVENTTYPE을 추가하려면 ([1], [2], [3] ..) PIVOT() 내부도

원하는만큼 테이블을 추가 SELECT에서 .

+0

도움이되었습니다. 고마워요! – samthebrand

관련 문제