2012-08-15 40 views
1

我想清理從查詢返回的一些數據。這個查詢:想回到一個假行如果沒有匹配我對(一年)

select seriesId, 
     startDate, 
     reportingCountyId, 
     countyId, 
     countyName, 
     pocId, 
     pocValue 
    from someTable 
where seriesId = 147 
    and pocid = 2 
    and countyId in (2033,2040) 

爲了通過的startDate

通常返回2縣的所有年份一致:

seriesId startDate reportingCountyId countyId countyName pocId pocValue 
147 2004-01-01 00:00:00.000 6910 2040 CountyOne  2 828 

147 2005-01-01 00:00:00.000 2998 2033 CountyTwo 2 4514 
147 2005-01-01 00:00:00.000 3000 2040 CountyOne  2 2446 

147 2006-01-01 00:00:00.000 3018 2033 CountyTwo 2 5675 
147 2006-01-01 00:00:00.000 4754 2040 CountyOne  2 2265 

147 2007-01-01 00:00:00.000 3894 2033 CountyTwo 2 6250 
147 2007-01-01 00:00:00.000 3895 2040 CountyOne  2 2127 

147 2008-01-01 00:00:00.000 4842 2033 CountyTwo 2 5696 
147 2008-01-01 00:00:00.000 4846 2040 CountyOne  2 2013 

147 2009-01-01 00:00:00.000 6786 2033 CountyTwo 2 2578 
147 2009-01-01 00:00:00.000 6817 2040 CountyTwo 2 1933 

147 2010-01-01 00:00:00.000 6871 2040 CountyOne  2 1799 
147 2010-01-01 00:00:00.000 6872 2033 CountyTwo 2 4223 

147 2011-01-01 00:00:00.000 8314 2033 CountyTwo 2 3596 
147 2011-01-01 00:00:00.000 8315 2040 CountyOne  2 1559 

但是請注意,第一項時,只在2004年,我想縣人爲我正在做的圖表返回CountyTwo的假行。這將足以填補它像只pocValue = 0

縣人

感謝!!!!!!!!

回答

1

試試這個(如果你需要一個空行對於countryid)

; with CTE AS 

(SELECT 2033 As CountryID UNION SELECT 2040), 

CTE2 AS 
(
     seriesId, startDate, reportingCountyId, 
     countyId, countyName, pocId, pocValue 
     from someTable where 
     seriesId = 147 and pocid = 2 and countyId in (2033,2040) 
     order by startDate 
) 

SELECT x1.CountyId, x2.*, IsNull(pocValue,0) NewpocValue FROM CTE x 
LEFT OUTER JOIN CTE2 x2 ON x1.CountyId = x2.reportingCountyId 
+0

的感謝!我很困惑如何將查詢添加到我的查詢中,甚至自己運行它。獲取大量語法錯誤(sql server) – user486480 2012-08-16 02:25:03

相關問題