我需要将行合并为一行以进行计算摘要(SQL Server 2014)。
我的SQL查询是:
import { withRouter } from "react-router";
class Component extends React.Component {
viewProfile = function () {
console.log("clicked");
this.props.history.push('/main');
}
render(){
return (
<Button color='primary' onClick={e => this.viewProfile()}>View Profile</Button>
)
}
}
export default withRouter(Component);
此查询的结果是:
SELECT
[c].[Iso],
SUM([r].[Quantity]) AS [Quantity],
SUM([r].[Amount]) AS [Amount]
FROM
[CarReport].[dbo].[Refuelling] [r]
INNER JOIN
[CarReport].[dbo].[Currency] [c] ON [r].[CurrencyId] = [c].[CurrencyId]
WHERE
[r].[DataId] = 15
AND [r].[IsDeleted] = 0
GROUP BY
[r].[CurrencyId], [c].[Iso]
我想得到这个结果:
CZK | 50.00 | 1350,00
EUR | 23.00 | 463,20
添加新货币(x)时,必须附加新货币的结果:
CZK/EUR | 50.00/23.00 | 1350,00/463,20
有人可以帮我解决这个话题吗?
非常感谢
答案 0 :(得分:0)
如果您正在运行SQL Server 2017,则可以添加另一级别的聚合并使用string_agg()
:
SELECT
STRING_AGG([Iso], '/') WITHIN GROUP(ORDER BY [Iso]) AS [Iso],
STRING_AGG([Quantity], '/') WITHIN GROUP(ORDER BY [Iso]) AS [Quantity],
STRING_AGG([Amount], '/') WITHIN GROUP(ORDER BY [Iso]) AS [Amount]
FROM (
SELECT
[c].[Iso],
SUM([r].[Quantity]) AS [Quantity]
SUM([r].[Amount]) AS [Amount]
FROM
[CarReport].[dbo].[Refuelling] [r]
INNER JOIN
[CarReport].[dbo].[Currency] [c] ON [r].[CurrencyId] = [c].[CurrencyId]
WHERE
[r].[DataId] = 15
AND [r].[IsDeleted] = 0
GROUP BY
[r].[CurrencyId], [c].[Iso]
) t
ORDER BY
的{{1}}子句使您在不同列中的值保持一致的顺序,因此您可以确定哪个数量和金额属于哪个货币(如果重要)。
答案 1 :(得分:0)
类似的事情也应该适用于早期版本的MSSQL。
;with subQuery as (
-- paste your base query here
-- extend it with one additional column:
-- ,ROW_NUMBER() OVER (ORDER BY ISO) RowNum
)
select
(select stuff((select '/' + convert(nvarchar(max), Iso) from subQuery order by RowNum for xml path('')), 1, 1, '')),
(select stuff((select '/' + convert(nvarchar(max), Quantity) from subQuery order by RowNum for xml path('')), 1, 1, '')),
(select stuff((select '/' + convert(nvarchar(max), Amount) from subQuery order by RowNum for xml path('')), 1, 1, ''))