我有两个数据库(MS SQL Server);一个具有当前的报告表集,另一个具有上周的报告表集。每周我都想比较每一个中的所有测量值(尽管每周的行数可能会有所不同)与前一周相比,并确保我的QTD和YTD数字正在增加。行的顺序可能每周都不同,所以无论我采用什么,都必须考虑到这一点。
另一个考虑因素是我有大约50个这些表要进行比较,因此手动执行每个表都不是一个选项。有一些错误日志也很棒,就像本周YTD值不比上周高的那样。
本周
+-------+------------+--------+
| Item | TimePeriod | Number |
+-------+------------+--------+
| Pigs | QTD | 28 |
| Pigs | YTD | 86 |
| Cows | QTD | 7 |
| Cows | YTD | 9 |
| Bears | QTD | 67 |
| Bears | YTD | 132 |
+-------+------------+--------+
上周
+-------+------------+--------+
| Item | TimePeriod | Number |
+-------+------------+--------+
| Bears | QTD | 55 |
| Bears | YTD | 120 |
| Pigs | QTD | 22 |
| Pigs | YTD | 80 |
| Cows | QTD | 5 |
| Cows | YTD | 10 |
+-------+------------+--------+
错误
错误:奶牛YTD当前周-9上周第10周
答案 0 :(得分:1)
也许这样的事情可以做到:
SELECT 'Error ' + CW.TimePeriod + ' Current week:' + CAST(CW.Number AS VARCHAR) + ' Prev week:' + CAST(PW.Number AS VARCHAR)
FROM [Current Week DB].Table CW
INNER JOIN [Previous DB].Table PW ON
CW.ITEM=PW.ITEM
AND CW.TIMEPERIOD=PW.TIMEPERIOD
AND CW.Number=PW.Number
加入所有列将使表格之间的行没有变化。需要明确更改表的标识符。
答案 1 :(得分:0)
您的问题中没有任何内容可以证明使用多个数据库或多个表格。
相反,请考虑使用这样的表格。
ITEM TIMEPERIOD WEEKNUM NUMBER
Bears QTD 2013-26 67
Bears QTD 2013-25 55
Bears YTD 2013-26 132
Bears YTD 2013-25 120
Cows QTD 2013-26 7
Cows QTD 2013-25 5
Cows YTD 2013-26 9
Cows YTD 2013-25 10
Pigs QTD 2013-26 28
Pigs QTD 2013-25 22
Pigs YTD 2013-26 86
Pigs YTD 2013-25 80
如果您有SQL Server 2012,那么基本查询相对简单明了。
select
item, timeperiod, weeknum, number,
number - lead (number)
over (partition by item, timeperiod
order by item, timeperiod, weeknum desc) as change
from table1;
ITEM TIMEPERIOD WEEKNUM NUMBER CHANGE
--
Bears QTD 2013-26 67 12
Bears QTD 2013-25 55 (null)
Bears YTD 2013-26 132 12
Bears YTD 2013-25 120 (null)
Cows QTD 2013-26 7 2
Cows QTD 2013-25 5 (null)
Cows YTD 2013-26 9 -1
Cows YTD 2013-25 10 (null)
Pigs QTD 2013-26 28 6
Pigs QTD 2013-25 22 (null)
Pigs YTD 2013-26 86 6
Pigs YTD 2013-25 80 (null)
如果您只想要那些具有负面更改的行,请使用上一个查询作为派生表,并添加WHERE子句
select *
from
(select
item, timeperiod, weeknum, number,
number - lead (number)
over (partition by item, timeperiod
order by item, timeperiod, weeknum desc) as change
from table1) t
where change < 0
and timeperiod = 'YTD';
ITEM TIMEPERIOD WEEKNUM NUMBER CHANGE
--
Cows YTD 2013-26 9 -1