1

我正在尝试查找特定值。如果 Region 的 Table1 的所有值都作为查找表 (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

感谢您的任何指导!

卡洛斯

4

3 回答 3

0

这有一个小技巧:

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

you need to translate 'ALL' to null, so when 'ALL' is selected, it cancels out the filter.

我想你要么使用 SSRS,要么使用上面的下拉菜单,但这里有一个链接:

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

于 2013-02-26T21:38:56.757 回答
0

将此查询与APPLY AND EXCEPT运算符一起使用

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上的演示

于 2013-02-26T22:54:03.027 回答
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

于 2013-02-26T22:03:35.947 回答