如何在 SQL Server 2000 中进行动态透视

发布于 2024-10-03 04:53:02 字数 153 浏览 0 评论 0原文

我想编写一个在 SQL Server 2000 中使用数据透视表的 SQL 语句。PIVOT 关键字在 SQL Server 2000 中不可用,因此我找到了一些使用 case 语句的示例,但这要求您事先知道列名,但我不会这样做。 t。如何创建一个数据透视表,根据其可用的数据动态生成列名称?

I want to write a SQL statement that uses a pivot in SQL Server 2000. The PIVOT keyword is not available in SQL Server 2000 so I found some examples that use a case statement but that requires that you know the column names beforehand which I won't. How do I do a pivot which dynamically generates the column names from the data it has available to it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟雨凡馨 2024-10-10 04:53:02

我们使用应用程序中的 CASE 语句创建 SQL 命令,并在数据库(任何数据库,而不是特定的 SQL 服务器)上触发它们。首先,我们使用一个查询确定数据透视列的数量及其名称,然后根据这些结果生成下一个查询。
因此,确定列的第一个查询看起来有点像:

SELECT DISTINCT myField FROM myTable

然后我们使用此结果中的所有值来构造一个 SQL 命令,其中为每个值生成一个 CASE 语句。

我们想要一个与数据库无关的解决方案,因此我们在数据库外部进行此处理,但我确信您可以在 SQL Server 本身的存储过程中执行相同的操作。

We create SQL commands with the CASE statements from our application and fire them at the database (any database, not specifically SQL server). First we determine the number of pivot columns and their names using one query, from those results we generate the next query.
So the first query to determine the columns looks somewhat like:

SELECT DISTINCT myField FROM myTable

Then we use all the values in this result to construct an SQL command where a CASE statement is generated for each value.

We wanted a databasebase agnostic solution so we do this processing outside the database but i'm sure you could do the same in a stored procedure withing SQL server itself.

如何视而不见 2024-10-10 04:53:02

我没有尝试在 SQL Server 2000 上复制 PIVOT,但我所做的是当我事先不知道列名时使用 PIVOT。我改为使用 ROW_NUMBER() 来确定列名称。你可以尝试一下。

I have not tried to replicate PIVOT on SQL Server 2000 but what I have done is use PIVOT when I do not know the column names beforehand. I had used ROW_NUMBER() to determine the column names instead. You can try that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文