SQL Lookup T1.ColumnA vs T2.ColumnA,如果T1.ColumnA中的所有5个值都列在T2.ColumnA中,则将T1.ColumnA替换为“ALL”

时间:2013-02-26 21:29:06

标签: sql sql-server sql-server-2008

我正在尝试执行特定值的查找。如果Table1 for Region的所有值都列为查找表(Table2)的一部分,则将Table1.Region字段替换为value ='ALL',基本上尝试对所有5个区域进行分组,并将值替换为“ALL”列出了5个区域(根据查找表中的值)当未列出所有区域时,请保留区域代码

Year   Region   Value
2012    A1      24
2012    B2      24
2012    C3      24
2012    D4      24
2012    E5      24
2012    A1      36
2012    B2      36
2012    C3      36
2012    D4      36
2012    E5      36
2013    A1      24
2013    B2      24


Lookup Table
Region  Value
1         A1
2         B2
3         C3
4         D4
5         E5

所需的结果

Year    Region Term
2012    ALL    24   <-- Note region change to all because there are 5 regions per above 
2012    ALL    36   <-- Note region change to all because there are 5 regions per above
2013    A1     24   <-- Region did not change because there were only 2 regions in source
2013    B2     24   <-- Region did not change because there were only 2 regions in source

我知道如何对数据进行分组,但需要进一步整合分组数据并替换为ALL

感谢任何方向!

卡洛斯

3 个答案:

答案 0 :(得分:0)

这有一个小技巧:

(@ var IS NULL或Table1.Region = @var)

你需要将'ALL'翻译为null,所以当选择'ALL'时,它会取消过滤器。

我想你要么使用SSRS,要么是高于此值,但这里有一个链接:

https://www.simple-talk.com/content/print.aspx?article=835#hr2

答案 1 :(得分:0)

您没有指定您正在使用的RDBMS,但您应该能够在所有数据库产品中使用以下内容:

select distinct t1.year,
  case 
    when t2.year is null and t2.value is null
    then t1.region
    else 'ALL' End Region,
  t1.value
from table1 t1
left join
(
  select year, value
  from table1
  group by year, value
  having count(distinct region) = (select count(distinct value)
                                   from table2)
) t2
  on t1.year = t2.year
  and t1.value = t2.value

请参阅SQL Fiddle with Demo

答案 2 :(得分:0)

将此查询与APPLYEXCEPT运算符

一起使用
SELECT t1.Year, CASE WHEN o.Value IS NULL THEN 'ALL' ELSE t1.Region END AS Region,
       t1.Value
FROM dbo.test7 t1 OUTER APPLY (                               
                               SELECT Value
                               FROM test8 
                               EXCEPT                               
                               SELECT Region
                               FROM test7 t2
                               WHERE t1.Year = t2.Year
                                 AND t1.Value = t2.Value                                                             
                               ) o
GROUP BY t1.Year, CASE WHEN o.Value IS NULL THEN 'ALL' ELSE t1.Region END, 
         t1.Value 

SQLFiddle上的演示