SELECT * FROM表除了聚合功能

时间:2019-03-13 22:30:02

标签: sql join aggregation

简短上下文: 我想列出所有公司的清单,除非它们属于“国防”或“政府”部门,以及他们在培训课程上的总花费。仅显示总金额超过1000的公司。

所以我写了以下查询:

SELECT NAME, ADDRESS, ZIP_CODE, CITY, SUM(FEE-PROMOTION) AS "Total spent on training at REX"
FROM COMPANY INNER JOIN PERSON ON (COMPANY_NUMBER = EMPLOYER) INNER JOIN ENROLLMENT ON (PERSON_ID = STUDENT)
WHERE SECTOR_CODE NOT IN (SELECT CODE 
              FROM SECTOR 
              WHERE DESCRIPTION = 'Government' OR DESCRIPTION = 'Defense')
GROUP BY NAME, ADDRESS, ZIP_CODE, CITY
HAVING SUM(FEE-PROMOTION) > 1000
ORDER BY SUM(FEE-PROMOTION) DESC

现在我真正需要的是,而不是定义COMPANY表中的每一列,我想使用*显示COMPANY表中的所有列。

SELECT * (all tables from COMPANY here), SUM(FEE-PROMOTION) AS "Total spent on training at REX"
FROM COMPANY INNER JOIN PERSON ON (COMPANY_NUMBER = EMPLOYER) INNER JOIN ENROLLMENT ON (PERSON_ID = STUDENT)
WHERE SECTOR_CODE NOT IN (SELECT CODE 
              FROM SECTOR 
              WHERE DESCRIPTION = 'Government' OR DESCRIPTION = 'Defense')
GROUP BY * (How to fix it here?)
HAVING SUM(FEE-PROMOTION) > 1000
ORDER BY SUM(FEE-PROMOTION) DESC

我可以在SELECT中定义COMPANY中的每一列,并且该解决方案可以完成任务(如第一个示例中所示),但是如何使用“ SELECT * from table COMPANY”来使查询更短?

1 个答案:

答案 0 :(得分:1)

关键思想是在子查询中进行汇总,以获取公司的总支出。这使您可以从外部查询中删除聚合:

select c.*, pe.total_spend
from company c join
     sector s
     on c.sector_code = s.code left join
     (select p.employer, sum(e.fee - e.promotion) as training_spend
      from person p join
           enrollment e
           on p.person_id = e.student
      group by p.employer
     ) pe
     on pe.employer = c.company_number
where s.sector not in ('Government', 'Defense') and
      pe.total_spend > 1000