gpt4 book ai didi

c# - 如何使用动态列来转换普通的 sql 查询

转载 作者:太空宇宙 更新时间:2023-11-03 11:19:53 24 4
gpt4 key购买 nike

我有一个返回如下内容的 Sql 查询:

Rating as at    Rating type    Rating
--------------------------------------
6/7/2012 Type1 A
6/7/2012 Type2 A+
6/7/2012 Type3 B
8/7/2012 Type1 C
8/7/2012 Type2 C+
8/7/2012 Type3 B
8/7/2012 Type4 A

如您所见,评级类型是动态的,我想在数据透视表中显示它,但我真的不知道如何实现。我想要的最终结果如下所示:

Rating as at    Type1   Type2   Type3   Type4
6/7/2012 A A+ B
8/7/2012 C C C+ A

我想知道如何使用 sql 实现此目的。或者我最好如何使用 LINQ C# 来完成它??

帮助将不胜感激。谢谢。

最佳答案

根据下面 OP 的评论更新了答案 - 此更新现在会将结果转换为字母等级

以下结合使用了 SQL Server 的数据透视运算符 (MSDN) 以及 EXEC 语句 (MSDN)。

T-SQL 解决方案将处理完全动态的列。

--Create a temp table to hold values
CREATE TABLE #MyTable (
[Rating as at] DATE,
[Rating type] Nvarchar(30),
Rating FLOAT )

INSERT INTO #MyTable ([Rating as at],[Rating type],Rating) VALUES ('6/7/2012','Type1', 1)
INSERT INTO #MyTable ([Rating as at],[Rating type],Rating) VALUES ('6/7/2012','Type2', 3)
INSERT INTO #MyTable ([Rating as at],[Rating type],Rating) VALUES ('6/7/2012','Type3', 5)
INSERT INTO #MyTable ([Rating as at],[Rating type],Rating) VALUES ('8/7/2012','Type1', 5)
INSERT INTO #MyTable ([Rating as at],[Rating type],Rating) VALUES ('8/7/2012','Type2', 2)
INSERT INTO #MyTable ([Rating as at],[Rating type],Rating) VALUES ('8/7/2012','Type3', 4)
INSERT INTO #MyTable ([Rating as at],[Rating type],Rating) VALUES ('8/7/2012','Type4', 1)
SELECT DISTINCT [Rating type] INTO #MyTableDistinct FROM #MyTable

--Create a string of dynamic fields
DECLARE @MyVar1 nvarchar(max),@MyVar2 nvarchar(max)
SELECT @MyVar1 = COALESCE(@MyVar1,'') + '[' + [Rating type] + ']' + ', ' FROM #MyTableDistinct
SELECT @MyVar1 = LEFT(@MyVar1, LEN(@MyVar1) - 1)

--Create a string of dynamic CASE statements to be used to convert pivoted results to letter grades
--Update the CASE steatement to handle different grade types
SELECT @MyVar2 = COALESCE(@MyVar2,'') + 'CASE WHEN [' + [Rating type] + '] IS NULL THEN ''N/A'' WHEN [' + [Rating type] + '] > 4 THEN ''A'' WHEN [' + [Rating type] + '] > 3 THEN ''B'' WHEN [' + [Rating type] + '] > 2 THEN ''C'' ELSE ''F'' END AS [' + [Rating type] + '], ' FROM #MyTableDistinct
SELECT @MyVar2 = LEFT(@MyVar2, LEN(@MyVar2) - 1)

--Build a SQL string to be later execute
--This is where all of the PIVOT magic happens
DECLARE @MySQLStatement nvarchar(max)
SET @MySQLStatement = 'SELECT [Rating as at],' + @MyVar1 + ' INTO #MyPivotTable FROM
(SELECT [Rating as at],[Rating type],Rating from #MyTable) AS p1
PIVOT (
avg(Rating) FOR [Rating type] IN (' + @MyVar1 + ')
) as p2;SELECT [Rating as at], ' + @MyVar2 + ' FROM #MyPivotTable;DROP TABLE #MyPivotTable;'

--Execute the SQL string
EXEC(@MySQLStatement)


DROP TABLE #MyTableDistinct
DROP TABLE #MyTable

关于c# - 如何使用动态列来转换普通的 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11379784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com