如果我的配对没有匹配(一年),想要返回一个假行

时间:2012-08-15 19:26:00

标签: sql sql-server

我想清理查询返回的一些数据。这个查询:

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年的CountyOne。我想为CountyTwo返回一个假行,用于我正在做的图表。仅使用pocValue = 0就可以像CountyOne一样填充它。

!!!!!!!!

感谢

1 个答案:

答案 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