来自答案from here我构建了一个对我有好处的解决方案,但我仍然有一个问题。
我有 table :
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
我构建此 View 来连接“年”+“月”并进行 IF 语句: 我从 Future 和 Current 列中获取的新 Value 列中的值 - 当 Current 值为 null 时,获取 Future 值并乘以 Multiply,否则获取 Current 值并乘以 Multiply(甚至 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
由此,我通过动态枢轴创建此 View 。
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);
正如您所看到的,新 View 中的列没有以良好的方式排序..而不是 2017 - 1、2017 - 2、2017 - 3 我有 2017 - 1、2017 - 10、2017 - 11、2017 - 12, 2017 - 2. 你能帮我如何正确排序吗?
最佳答案
根据有限的信息,您想要的是基于“年+月”的串联字符串对列进行排序。
您需要为月份添加前缀“0”(表示 1 月 - 9 月),不添加前缀表示 10 月 - 12 月。
所以实际上您将实现这一目标。
ID | 2017 - 01 | 2017 - 02 | 2017 - 03 | ..... | 2017 - 09 |2018 - 10 |2018 - 11||2018 - 12|
SELECT ID = ID,
[Date] = [Date],
[Value] = [Value]
FROM
(
SELECT ID,
CAST([Year] AS VARCHAR(30))+' - '+RIGHT('0'+CAST([Month] AS VARCHAR(30)), 2) 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;
关于sql - 动态月份和年份枢轴,排序不良,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49378049/