2009-07-01 52 views
2

我有3個表:如何在SQL Server 2005/8上獲取類似於表的查詢結果?

users (id, name) 

currency (id, name) 

accounts (id, user_id, currency_id, amount) 

而且我想從accounts讀取數據,並在表狀觀目前它:

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

owneraccounts.ownerIDcurrency1,2,3 - (SELECT id FROM currency WHERE name = '1',etc)

我只能得到一個特定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] 

對於users表中的每個對象,是否可以得到相同的結果?沒有使用Reporing Service等。

+0

組合(user_id,currency_id)在帳戶中是唯一的嗎? – balpha 2009-07-01 17:11:07

+0

是的,它是獨一無二的。 – abatishchev 2009-07-01 17:24:28

回答

2

使用數據透視表和動態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) 

這在SQL Server中進行測試2005

2

聽起來就像你想要一個數據透視表。如果您的貨幣數量不同,但是仍然可以通過使用dynamiclly寫入的sql來完成,那將會很困難。

下面是從MSDN資源,介紹如何使用數據透視表:http://msdn.microsoft.com/en-us/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 
+0

感謝您的回答!我將閱讀更多關於數據透視表的內容。關於你的例子 - 我可以在哪裏添加'FROM currency AS C' - 據我瞭解, – abatishchev 2009-07-01 17:29:05