简体   繁体   English

如何在SQL Server 2005/8上获得类似表的查询结果?

[英]How to get table-like query result on SQL Server 2005/8?

I have 3 tables: 我有3张桌子:

users (id, name)

currency (id, name)

accounts (id, user_id, currency_id, amount)

And I want to read the data from accounts and present it in table-like view: 我想从accounts读取数据并以表格形式显示:

owner  currency1 currency2 currency3
1      0         0         0
2     10        20        30
3      0         5        10

Where owner is ID of accounts.owner , currency1,2,3 - (SELECT id FROM currency WHERE name = '1',etc) 其中ownerIDaccounts.ownercurrency1,2,3 - (SELECT id FROM currency WHERE name = '1',etc)

I can get such result only for one specific ID: 我只能针对一个特定的ID获得这样的结果:

SELECT
  SELECT amount FROM accounts WHERE currency = (SELECT id FROM currency WHERE name = 'currency1') AND owner = @user) AS [currency1],
  SELECT amount FROM accounts WHERE currency = (SELECT id FROM currency WHERE name = 'currency2') AND owner = @user) AS [currency2],
  SELECT amount FROM accounts WHERE currency = (SELECT id FROM currency WHERE name = 'currency2') AND owner = @user) AS [currency2]

Is it possible to get the same result for every object in users table? users表中的每个对象都能获得相同的结果吗? Without using Reporing Service, etc. 不使用重订服务等

Sounds like you want a Pivot table. 听起来好像您想要数据透视表。 It will be difficult to do if you have a varying number of rows in currency, but could still be done by using dynamiclly written sql. 如果您使用不同数量的货币行,将很难做到,但是仍然可以通过使用动态编写的sql来完成。

Here's a resource from MSDN that explains how to use the pivot table: http://msdn.microsoft.com/en-us/library/ms177410.aspx 这是MSDN的资源,解释了如何使用数据透视表: http : //msdn.microsoft.com/zh-cn/library/ms177410.aspx

SELECT u.name, [1] AS Currency1, [2] AS Currency2, [3] AS Currency3
FROM 
(SELECT u.Name AS UserName, c.Currency_ID, a.Amount
FROM Accounts AS a WITH(NOLOCK)
JOIN Users u WITH(NOLOCK) ON a.user_id = u.user_id
) p
PIVOT
(
SUM (p.Amount)
FOR p.Currency_id IN
( [1], [2], [3] )
) AS pvt
ORDER BY pvt.UserName

Use a pivot table and dynamic SQL to retrieve the columns 使用数据透视表和动态SQL检索列

    DECLARE @columns VARCHAR(2000)
    SELECT @columns = STUFF(( SELECT DISTINCT TOP 100 PERCENT
    '],[' + c.name
    FROM currency AS c
    ORDER BY '],[' + c.name
    FOR XML PATH('')
    ), 1, 2, '') + ']'

    DECLARE @query NVARCHAR(4000)
    SET @query = N'SELECT UserName, ' + @columns +
    'FROM 
    (SELECT u.Name AS UserName, c.name AS CurrencyName, a.Amount
    FROM Accounts AS a WITH(NOLOCK)
    JOIN Users u WITH(NOLOCK) ON a.user_id = u.user_id
    JOIN Currency c WITH(NOLOCK) ON a.currency_id = c.currency_id
    ) p
    PIVOT
    (
    SUM (p.Amount)
    FOR p.CurrencyName IN
    ( '+ @columns +')
    ) AS pvt
    ORDER BY UserName'

EXECUTE(@query)

This was tested in SQL Server 2005 这已在SQL Server 2005中进行了测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM