从这里的答案中,我构建了一个对我有好处的解决方案,但我仍然有一个问题。
我有桌子:
ID | Year | Month | Multiply | Future | Current
123 | 2017 | 1 | 1.0 | 25 | null
123 | 2017 | 2 | 1.0 | 19 | 15
123 | 2017 | 3 | 1.0 | 13 | 0
123 | 2017 | 4 | 1.0 | 22 | 14
123 | 2017 | 5 | 1.0 | 13 | null
... | .... | ... | ... | .. | ..
123 | 2018 | 1 | 1.0 | 25 | 10
123 | 2018 | 2 | 1.0 | 25 | 10
... | .... | ... | ... | .. | ..
124 | 2017 | 1 | 1 | 10 | 5
124 | 2017 | 2 | 1 | 15 | 2
... | .... | ... | ... | .. | ..
124 | 2018 | 1 | 1 | 20 | 0
我构建此视图以连接年 + 月并制作 IF 语句:我从 Future 和 Current 列获得的新 Value 列中的值 - 当 Current 值为 null 时,获取 Future 值并乘以 Multiply,否则获取 Current 值和乘以乘(甚至为 0)。在它旁边,当从 Future 列获取值时,我需要添加一个“F”前缀。
ID | Date | Value |
123 | 2017 - 1 | F25 |
123 | 2017 - 2 | 15 |
123 | 2017 - 3 | 0 |
.. | .. | .. |
代码:
SELECT ID = ID,
[Date] = [Date],
[Value] = [Value]
FROM ( SELECT ID,
cast([Year] as varchar(30)) + ' - ' + cast([Month]as varchar(30)) as [Date],
[Multiply],
case when [Current] IS NULL /*OR [Current] = 0*/
then 'F' + CAST([Future] * [Multiply] as varchar(30))
else CAST([Current] * [Multiply] as varchar(30))
end as Value
FROM dbo.CurrentFuture
) AS t
从这里我通过动态枢轴制作这个视图。
ID | 2017 - 1 | 2017 - 10 | 2017 - 11 | 2017 - 12 | 2017 - 2 | ... | 2018 - 1 | ...
123 | F25 | .. | .. | .. | 15 | ... | 10 | ...
124 | 5 | 2 | .. | .. | .. | ... | 0 | ...
代码:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME([Date])
from dbo.UpperView
group by [Date]
order by [Date]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT [ID],' + @cols + ' from
(
select [ID], [Date],[Value]
from [dbo].[UpperView]
) x
pivot
(
max([Value])
for [Date] in (' + @cols + ')
) p '
execute(@query);
如您所见,新视图中的列没有很好地排序.. 而不是 2017 - 1, 2017 - 2, 2017 - 3 我有 2017 - 1, 2017 - 10, 2017 - 11, 2017 - 12, 2017 - 2. 你能帮我如何正确排序吗?