SQL摘要查询

时间:2018-07-29 15:21:07

标签: sql-server

我有一个SQL查询的输出。我想优化结果以使其更有意义。

查询返回以下结果

Name    Date    Measure No    Measure Value    Measure Percent
--------------------------------------------------------------
xyz     30/06/18    1           33857               18
xyz     30/06/18    2           11056               45
xyz     30/06/18    4           46487               28
xyz     30/06/18    5           34376               48
abc     30/06/18    1           24982               27
abc     30/06/18    2           43234               45
abc     30/06/18    4           13791               25
abc     30/06/18    5           22261               20
lmn     30/06/18    1           45728               41
lmn     30/06/18    2           31480               48
lmn     30/06/18    4           32750               26
lmn     30/06/18    5           44771               36

我想进一步总结。我想将度量1和度量2的结果添加到特定名称和日期的临时度量3中。查询结果应该是这样

Name    Date    Measure No  Measure Value   Measure Percent
-----------------------------------------------------------
xyz 30/06/18    1   33857   18
xyz 30/06/18    2   11056   45
xyz 30/06/18    3   44913   63
xyz 30/06/18    4   46487   28
xyz 30/06/18    5   34376   48
abc 30/06/18    1   24982   27
abc 30/06/18    2   43234   45
abc 30/06/18    3   68216   72
abc 30/06/18    4   13791   25
abc 30/06/18    5   22261   20
lmn 30/06/18    1   45728   41
lmn 30/06/18    2   31480   48
lmn 30/06/18    3   77208   89
lmn 30/06/18    4   32750   26
lmn 30/06/18    5   44771   36

我该怎么做?

2 个答案:

答案 0 :(得分:1)

如果您只想添加带有新的Measure No 3的行,这些行分别是“名称”和“日期”的值和1和2的百分比之和,那么这应该为您完成:

SELECT [Name], [Date], [Measure No], [Measure Value], [Measure Percent]
FROM YourQueryResult

UNION ALL

SELECT [Name], [Date], 3, SUM([Measure Value]), SUM([Measure Percent])
FROM YourQueryResult
WHERE [Measure No] IN (1, 2)
GROUP BY [Name], [Date]

答案 1 :(得分:0)

根据您的输出,您可能需要unionunion all

select col1,col2.. from your 1stQueryoutput
union 

select col1,col2.. from your 2ndQueryoutput

select col1,col2.. from your 1stQueryoutput
union all

select col1,col2.. from your 2ndQueryoutput