此Excel以相同的格式导入到SQL表(SQL Server 2012)中,并在工厂和年份中增加了两列。
下面是我用于报告的SQL视图。如您所见,月份变成了行,值列变成了行:
+---------+------+-------+------+--------+
| Plant | Year | Month | A | B |
+---------+------+-------+------+--------+
| Plant X | 2019 | 1 | 526 | 16 |
| Plant X | 2019 | 2 | 786 | 54 |
| Plant X | 2019 | 3 | 1800 | 85 |
| Plant X | 2019 | 4 | 9780 | 15 |
| Plant X | 2019 | 5 | 9780 | (null) |
| Plant Y | 2019 | 1 | 4080 | 128 |
| Plant Y | 2019 | 2 | 1387 | 179 |
+---------+------+-------+------+--------+
这是上面的sql视图的Fiddle。
CREATE TABLE Test
([Plant] varchar(13), [Year] int, [Month] int, [A] decimal(18,2), [B] decimal(18,2))
;
INSERT INTO Test
([Plant], [Year], Month, A, B)
VALUES
('Plant X', 2019,1,526 ,16 ),
('Plant X', 2019,2,786 ,54),
('Plant X', 2019,3, 1800,85),
('Plant X', 2019,4, 9780,15),
('Plant X', 2019,5, 9780,NULL),
('Plant Y', 2019,1,4080 ,128 ),
('Plant Y', 2019,2,1387 ,179)
;
是否可以在我的SQL视图中进行计算,如上面的Excel图像所示?如果是,您可以举个例子吗?
由于我也将数据存储在SQL表中,就像Excel结构(以月为列)那样,以这种格式进行计算更有意义吗?
谢谢。
答案 0 :(得分:1)
这是一个问题,必须取消一些列的旋转并转向另一列。为了取消透视,我使用了CROSS APPLY
和table values constructor
,它们非常通用(与unpivot运算符不同)。我还使用交叉表方法来透视数据。
SELECT Plant, [Year], colName,
SUM(CASE WHEN [Month] = 1 THEN colValue END),
SUM(CASE WHEN [Month] = 2 THEN colValue END),
SUM(CASE WHEN [Month] = 3 THEN colValue END),
SUM(CASE WHEN [Month] = 4 THEN colValue END),
SUM(CASE WHEN [Month] = 5 THEN colValue END),
SUM(CASE WHEN [Month] = 6 THEN colValue END),
SUM(CASE WHEN [Month] = 7 THEN colValue END)
FROM Test
CROSS APPLY( VALUES( 'A', A),( 'B', B)) AS x(colName, colValue)
GROUP BY Plant, [Year], colName
ORDER BY Plant, [Year], colName;
答案 1 :(得分:1)
以一种快速的方式并通过您的示例表,可以像这样:
select t.*
, Calculated = (
select cast(round(sum(B) * 1000000 / sum(A), 0) as int)
from Test
where Plant = t.Plant
and [Year] = t.[Year]
and [Month] <= t.[Month]
having sum(A) <> 0
)
from Test t
答案 2 :(得分:0)
您还可以通过在TSQL中使用PIVOT和UNPIVOT来实现。
SELECT [Plant]
,[Year]
,[newColumn]
,SUM([1]) [1]
,SUM([2]) [2]
,SUM([3]) [3]
,SUM([4]) [4]
,SUM([5]) [5]
FROM [Test]
UNPIVOT(Orders FOR newColumn IN (
A
,B
)) AS unpvt
PIVOT(SUM([Orders]) FOR [Month] IN (
[1]
,[2]
,[3]
,[4]
,[5]
)) AS PivotTable
GROUP BY [Plant]
,[Year]
,[newColumn]