SQL 服务器 - 比较多个表中的有序列

SQL Server - Compare ordered columns from multiple tables

我有三个表格,里面装满了项目观察结果,每个表格都有以下列: 表 2015:ItemName、ItemCount 表 2014:ItemName、ItemCount 表 2013:ItemName,ItemCount

并且我想从 Table2015 中获取每个 ItemName 的 3 个最高计数,如果 Table2015 中该 ItemName 的最高计数大于它的最高计数,则在报告中标记该行的特殊列在 Table2014 和 Table2013.

我有以下方法可以从 Table2015 中获取高计数,我不确定如何继续获取我需要的内容。我是否应该将另一个 CTE 与其他表一起使用,并以某种方式将其加入最终 select?

with counts as (
select e.ItemName, e.ItemCount, row_number() over (partition by e.ItemName order by cast(e.ItemCount as int) desc) as rk
from Table2015 e where e.ItemCount <> 'X')

select s.*, 
from counts s
where s.rk<4
order by s.ItemName,s.rk;

只要不同年份的item名称一致,就可以join到其他表中

with counts as (
select e.ItemName, e.ItemCount, row_number() over (partition by e.ItemName order by cast(e.ItemCount as int) desc) as rk
from Table2015 e where e.ItemCount <> 'X')

select s.ItemName
   , s.ItemCount
   , CASE WHEN CAST(t15.ItemCount AS INT) > ISNULL(CAST(t14.ItemCount AS INT), 0) THEN 1 ELSE 0 END AS GreaterThan2014
   , CASE WHEN CAST(t15.ItemCount AS INT) > ISNULL(CAST(t13.ItemCount AS INT), 0) THEN 1 ELSE 0 END AS GreaterThan2013
from counts s
    inner join counts t15 ON s.ItemName = t15.ItemName and t15.rk = 1
    left join (
        select ItemName, MAX(CASE WHEN IsNumeric(ItemCount) = 1 THEN CAST(ItemCount AS INT) ELSE -1 END)
        from Table2014 
        where ItemCount <> 'X' 
        group by ItemName
   ) t14 on s.ItemName = t14.ItemName 
    left join (
        select ItemName, MAX(CASE WHEN IsNumeric(ItemCount) = 1 THEN CAST(ItemCount AS INT) ELSE -1 END)
        from Table2013
        where ItemCount <> 'X' 
        group by ItemName
   ) t13 on s.ItemName = t13.ItemName 

where s.rk<4
order by s.ItemName,s.rk;

此外,您真的不应该在计数字段中使用 'X' 作为可能性。如果您正在数数,则应输入 INT.