0

Given data like this:

SHQSCriteria            PropertyRef ReplacementYear
Energy Efficient            31          2014/15
Healthy, Safe & Secure      31          2012/13
Energy Efficient            462         2014/15
Healthy, Safe & Secure      462         2012/13
Free From Serious Disrepair 497         2012/13
Healthy, Safe & Secure      497         2012/13
Tolerable Standard          497         2012/13
Free From Serious Disrepair 498         2012/13
Healthy, Safe & Secure      498         2013/14
Tolerable Standard          498         2014/15

I want to pull out all the properties that fail more than one criterion, with the year that they fail the second criterion.

So, I want records that appear in the above list at least twice, but the replacement year is the second chronologically. Like this:

PropertyRef ReplacementYear
   31           2014/15
   462          2014/15
   497          2012/13
   498          2013/14

Please note that in this example properties 497 and 498 both fail three criteria. 497 fails all in the same year, so we should return that year. But 498 fails in 3 different years so we should return the second year.

4

2 に答える 2

2

CTEおよびrow_number()Sql-Server 2008 以降を使用してこれを試してください。

;with cte as (
  select propertyRef, replacementYear,
         row_number() over (partition by propertyref order by replacementYear) rn
  from table
)
select * from cte
where rn = 2
于 2013-02-19T15:42:55.863 に答える
2

共通のテーブル式を使用して、各 PropertyRef 内の年を順序付け (および番号付け) し、それをデータに結合して、PropertyRef ごとに 2 番目の年を指定できます。

WITH cte AS (
            SELECT  PropertyRef,
                    Years,
                    ROW_NUMBER() OVER (PARTITION BY propertyref ORDER BY years) as RowNumber
            FROM    data
)
SELECT      d.PropertyRef,
            cte.Years
FROM        data d
INNER JOIN  cte
ON          cte.PropertyRef = d.PropertyRef
AND         cte.RowNumber = 2
GROUP BY    d.PropertyRef,
            cte.Years
HAVING      COUNT(*) > 1
于 2013-02-19T15:36:45.657 に答える