我有这张桌子:
Year Month| User| Player | Manager
1996-06 | 1256| 2 | 1
1997-07 | 1243| 5 | 2
并试图将其转动以便返回:
| 1997-06|1996-07
User | 1256 | 1243
Player | 2 | 5
Manager| 1 | 2
然而,我不确定为什么我的下面的脚本会返回不同的内容:
DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', p.' + QUOTENAME([User])
FROM (SELECT p.[User] FROM dbo.practise AS p
GROUP BY p.[User]) AS x;
SET @sql = N'
SELECT ' + STUFF(@columns, 1, 2, '') + '
FROM
(
SELECT [year month], [User]
FROM dbo.practise AS p
) AS j
PIVOT
(
SUM([User]) FOR [year month] IN ('
+ STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
+ ')
) AS p;';
PRINT @sql;
EXEC sp_executesql @sql;
它返回:
1256|1243
1 Null|Null
不确定我做错了什么:/
答案 0 :(得分:1)
你可以简化一下
示例强>
var data = JSON()
if(CustomDefaults().checkObject(key: "list2")){
data = JSON.init(parseJSON: CustomDefaults().getObject(key: "list2") as? String ?? "")
}
else{
var bomb = [JSON]()
bomb.append(["name":"Happy","url":"google.com"])
let finalData = JSON(bomb).rawString() ?? "" //data.rawString() ?? ""
CustomDefaults().setObject(value: finalData, key: "list2")
}
<强>返回强>
Declare @SQL varchar(max) = '
Select *
From (
Select [Year Month]
,B.*
From practise
Cross Apply (values (''User'' ,cast([User] as varchar(max)))
,(''Player'' ,cast(Player as varchar(max)))
,(''Manager'',cast(Manager as varchar(max)))
) B (Item,Value)
) A
Pivot (max([Value]) For [year month] in (' + Stuff((Select Distinct ','+QuoteName([year month])
From practise
Order By 1
For XML Path('')),1,1,'') + ') ) p
Order by 1 Desc'
Exec(@SQL);
--Print @SQL
生成的SQL看起来像这样
Item 1996-06 1997-07
User 1256 1243
Player 2 5
Manager 1 2