SQL Server 2012
目标:将多个货币行合并为一个字符串,其间有空格。
我尝试了各种编辑和修改,但我似乎无法做到这一点。
以下是我正在查看的数据:
Table1.[Misc Amount]
Table2.Taxes
我的专栏名称有一个空格,我猜测它真的让xml路径生气。
使用的声明:
DECLARE @Misc nvarchar(30)
SET @Misc = (SELECT [Misc Amount] FROM Table1 WHERE Order=33532)
SELECT @Misc + ' '+ STUFF((SELECT ' ' + SUM(TaxAmount ) AS [text()]
FROM Table2
WHERE Order=33532
GROUP BY Code FOR XML Path('')), 1,0,'')
我也尝试过字符串值[node()],玩1,2等等的位置
我的结果数据是:
10.00 0.006.084.50
我想要的是
10.00 0.00 6.08 4.50
我喜欢排除0.00,但此刻我只对我的空间感到高兴......我真的很讨厌陈述。你们中的任何一位大师都有办法帮助我吗?
答案 0 :(得分:3)
你已经有了一个解决方案,这很好,但我认为以下可能更简洁,它完全基于设置和无法使用:
(从Chris Albert的解决方案中借用了DDL,为此付出了代价!)
CREATE TABLE #MiscAmount ([Order] int, [Misc Amount] money)
CREATE TABLE #Taxes ([Order] int, Code int, TaxAmount money)
INSERT INTO #MiscAmount ([Order], [Misc Amount]) VALUES
(33532, 10.00)
,(1111, 11.00);
INSERT INTO #Taxes ([Order], Code, TaxAmount) VALUES
(33532, 1, 0.00)
,(33532, 2, 6.08)
,(33532, 2, 1.00) --2 of Code=2 (as you are using `GROUP BY Code`)
,(33532, 3, 4.50)
,(1111, 1, 1.11);
SELECT m.[Misc Amount]
,STUFF(
(
SELECT ' ' + CAST(SUM(t.TaxAmount) AS VARCHAR(100))
FROM #Taxes AS t
WHERE t.[Order]=m.[Order]
GROUP BY t.Code
FOR XML PATH('')
),1,1,'') AS CombinedTaxAmount
FROM #MiscAmount AS m
GO
DROP TABLE #MiscAmount
DROP TABLE #Taxes
结果
Misc Amount CombinedTaxAmount
10,00 0.00 7.08 4.50
11,00 1.11
答案 1 :(得分:2)
您的TaxAmount列可能是数值数据类型。因此,省略了包含空格的字符串。将其转换为字符串数据类型和您的业务。
CREATE TABLE #MiscAmount ([Order] int, [Misc Amount] money)
CREATE TABLE #Taxes ([Order] int, Code int, TaxAmount money)
INSERT INTO #MiscAmount ([Order], [Misc Amount]) VALUES (33532, 10.00)
INSERT INTO #Taxes ([Order], Code, TaxAmount) VALUES
(33532, 1, 0.00),
(33532, 2, 6.08),
(33532, 3, 4.50)
DECLARE @Misc nvarchar(30)
SET @Misc = (SELECT [Misc Amount] FROM #MiscAmount WHERE [Order] = 33532)
SELECT @Misc + ' '+ STUFF((SELECT ' ' + CAST(SUM(TaxAmount) AS varchar(50)) AS [text()]
FROM #Taxes
WHERE [Order] = 33532
GROUP BY Code FOR XML Path('')), 1,0,'')
DROP TABLE #MiscAmount
DROP TABLE #Taxes