sql中的数字查询

发布于 2024-08-30 07:36:42 字数 231 浏览 6 评论 0原文

我在 sql as 中有一个表

User | Account
-----+---------
  1  |   25
  1  |   31
  1  |   35
  1  |   44
  1  |   50
  1  |   59 

,并需要在三列中输出

  1  |   25   |  31
  1  |   35   |  44
  1  |   50   |  59

I have table in sql as

User | Account
-----+---------
  1  |   25
  1  |   31
  1  |   35
  1  |   44
  1  |   50
  1  |   59 

and output need in as three columns

  1  |   25   |  31
  1  |   35   |  44
  1  |   50   |  59

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

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

发布评论

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

评论(1

亢潮 2024-09-06 07:36:42

好的,正如您所说的 sql server 2005,我将向您展示使用 rownumber 的实现。

假设:
1.) 基组应为 Id。 ID 1和ID 2的账户不能在同一行。

使用模拟数据的解决方案:

SELECT  ID,
        Max(Case When OrderCaluse = 0 Then Account Else NULL END) AS Account1,
        Max(Case When OrderCaluse = 1 Then Account Else NULL END) AS Account2
FROM
( 
    Select  ID,
            Account,
            (RowNum+1)/2 As GroupClause, 
            (RowNum+1)%2 as OrderCaluse
    FROM
    (
        Select  *,
                ROW_NUMBER() Over (Partition by Id order by account) As RowNum
        FRom
        (
            Select 1 as Id, 25 as Account
            Union ALL
            Select 1, 31
            Union ALL
            Select 1, 35
            Union ALL
            Select 1, 44
            Union ALL
            Select 1, 50
            Union ALL
            Select 1, 59
        ) AS UserAccount
    ) AS T
) AS T1
Group By Id,GroupClause

结果:

1   25  31
1   35  44
1   50  59

希望有帮助。为了您的使用,只需删除内部临时表 UserAccount 并使用您的物理表。

Ok, so as u said sql server 2005, I will show you the implementation using rownumber.

Assumptions:
1.) Base group should be Id. Account of ID 1 and ID 2 should not be in the same row.

Solution with Mock data:

SELECT  ID,
        Max(Case When OrderCaluse = 0 Then Account Else NULL END) AS Account1,
        Max(Case When OrderCaluse = 1 Then Account Else NULL END) AS Account2
FROM
( 
    Select  ID,
            Account,
            (RowNum+1)/2 As GroupClause, 
            (RowNum+1)%2 as OrderCaluse
    FROM
    (
        Select  *,
                ROW_NUMBER() Over (Partition by Id order by account) As RowNum
        FRom
        (
            Select 1 as Id, 25 as Account
            Union ALL
            Select 1, 31
            Union ALL
            Select 1, 35
            Union ALL
            Select 1, 44
            Union ALL
            Select 1, 50
            Union ALL
            Select 1, 59
        ) AS UserAccount
    ) AS T
) AS T1
Group By Id,GroupClause

Result:

1   25  31
1   35  44
1   50  59

Hope it helps. For your use, just remove the Inner temp table UserAccount and use your physical table.

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