对联合查询求和

时间:2023-05-10
本文介绍了对联合查询求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我使用的是 Microsoft SQL Svr Mgmt Studio 2008.我无权创建临时表(公司限制创建或修改表的能力),或者我会用它来解决这个问题.

I'm using Microsoft SQL Svr Mgmt Studio 2008. I don't have access to create a temporary table (company restricts ability to create or modify tables) or I would use that to solve this problem.

我已经成功地使用联合查询来组合三个选择查询的结果.现在我试图总结联合的结果.

I have successfully used a union query to combine the results of three select queries. Now I am trying to sum the results of the union.

当我执行下面的查询时,我收到:

When I execute the query below I receive:

Incorrect syntax near the keyword 'GROUP'

然后当我通过我删除组时:

And then when I remove the group by I get:

Incorrect syntax near ')'

这是我目前的查询:

Select Period, PCC, SUM(BasicHits), SUM(FareHits), SUM(SearchHits)
From (

SELECT     AAAPeriod AS Period, 
AAAFromPCC AS PCC, 
- SUM(AAABasic) AS BasicHits,
- SUM(AAAFare) AS FareHits,
- SUM(AAASearch) AS SearchHits
FROM        HitsAaa
HAVING     (AAAPeriod = N'2010-10') 

UNION ALL

SELECT     AAAPeriod, 
AAAtoPCC,
SUM(AAABasic),
SUM(AAAFare),
SUM(AAASearch) 
FROM        HitsAaa
HAVING     (AAAPeriod = N'2010-10')

UNION ALL

SELECT      AgtPeriod, 
AgtPcc, 
SUM(AgtBasic),
SUM(AgtFare),
SUM(AgtSearch)
FROM          HitsAgent
HAVING      (AgtPeriod = N'2010-10')

)GROUP BY Period, PCC

对于之前的任何问题,我都无法找到解决方案.

I haven't been able to find a solution to this on any of the previous questions.

推荐答案

你需要给你的派生表取别名,你还必须使用一个带有 have 子句的 group by.

You need to alias your derived table, you must also use a group by with a having clause.

SELECT
  q1.Period, 
  q1.PCC, 
  SUM(q1.BasicHits), 
  SUM(q1.FareHits), 
  SUM(q1.SearchHits)
FROM (SELECT     
        AAAPeriod AS Period, 
        AAAFromPCC AS PCC, 
        - SUM(AAABasic) AS BasicHits,
        - SUM(AAAFare) AS FareHits,
        - SUM(AAASearch) AS SearchHits
      FROM HitsAaa
      GROUP BY 
        AAAPeriod, 
        AAAFromPCC
      HAVING (AAAPeriod = N'2010-10') 

      UNION ALL

      SELECT     
        AAAPeriod AS Period, 
        AAAtoPCC AS PCC,
        SUM(AAABasic) AS BasicHits,
        SUM(AAAFare) AS FareHits,
        SUM(AAASearch) AS SearchHits 
      FROM HitsAaa
      GROUP BY 
        AAAPeriod, 
        AAAtoPCC
      HAVING (AAAPeriod = N'2010-10')

      UNION ALL

      SELECT
        AgtPeriod AS Period, 
        AgtPcc AS PCC, 
        SUM(AgtBasic) AS BasicHits,
        SUM(AgtFare) AS FareHits,
        SUM(AgtSearch)  AS SearchHits
      FROM HitsAgent
      GROUP BY 
        AgtPeriod, 
        AgtPCC
      HAVING (AgtPeriod = N'2010-10')) q1 
GROUP BY 
  q1.Period, 
  q1.PCC

这篇关于对联合查询求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:如何手动卸载 Oracle? 下一篇:ORDER BY 和 LIMIT 后的 UNION

相关文章

最新文章