我有桌子:
带有值的价格(sellerId,usdBidPrice,usdAskPrice,eurBidPrice,eurAskPrice,gbpBidPrice,gbpAskPrice)
(1, 1, 1.1, 1.14, 1.16, 0.8, 0.9)
带有值的货币(ccyId,ccyDescription)
(1, 'USD'),
(2, 'EUR'),
(3, 'GBP')
期望的输出:
sellerId AvgPrice Ccy
1 1.05 1
1 1.15 2
1 0.85 3
我有这个工作样本,但不喜欢硬编码的值,没有它有什么选择吗?
DECLARE @usdId INT;
DECLARE @eurId INT;
DECLARE @gbpId INT;
SELECT @usdId = ccyId
FROM Currency (NOLOCK)
WHERE [description] = 'USD'
SELECT @eurId = ccyId
FROM Currency (NOLOCK)
WHERE [description] = 'EUR'
SELECT @gbpId = ccyId
FROM Currency (NOLOCK)
WHERE [description] = 'GBP'
SELECT
sellerId,
avgPrice,
CASE currencyType
WHEN 'USD' THEN @usdId
WHEN 'EUR' THEN @eurId
WHEN 'GBP' THEN @gbpId
ELSE NULL
END AS Ccy
FROM
(
SELECT
sellerId,
(usdBidPrice + usdAskPrice) / 2 AS USD,
(eurBidPrice + eurAskPrice) / 2 AS EUR,
(gbpBidPrice + gbpAskPrice) / 2 AS GBP
FROM Prices (NOLOCK)
) pricesRawData
unpivot
(
avgPrice for currencyType in (USD, EUR, GBP)
)marks
答案 0 :(得分:0)
您需要动态SQL和UNPIVOT:
SELECT sellerId,
AVG([Values]) as AvgPrice,
ccyId
FROM (
SELECT *
FROM #Prices) p
UNPIVOT (
[Values] FOR Price in ([USDBidPrice],[USDAskPrice],[EURBidPrice],[EURAskPrice],[GBPBidPrice],[GBPAskPrice])
) unpvt
INNER JOIN #Currency c
ON c.ccyDescription = LEFT(Price,3)
GROUP BY sellerId, ccyId
打印结果:
sellerId AvgPrice ccyId
1 1,05 1
1 1,15 2
1 0,85 3
执行后,您将获得此输出:
Render