SQL Server - 比较多个表中的有序列

时间:2015-02-24 18:01:45

标签: sql sql-server common-table-expression

我有三个完整的项目观察表,每个表都有以下列: 表2015:ItemName,ItemCount 表2014:ItemName,ItemCount Table2013:ItemName,ItemCount

并且我想从Table2015获得每个ItemName的3个最高计数,并在报告中标记该行,如果Table2015中该ItemName的最高计数大于其最高计数在表2014和表2013中。

我有以下内容来获得表2015中的高计数,我不知道如何继续得到我需要的东西。我应该在其他表中使用另一个CTE并以最终方式加入吗?

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;

1 个答案:

答案 0 :(得分:0)

只要项目名称在年份之间保持一致,您只需要加入其他表格

即可
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