mysql求和并显示所有注册表

f0ofjuux  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(233)

我试图合计和显示mysql中的所有注册表。我有个问题:

select `deliverables`.*, 
       `users`.`first_name`, 
       `users`.`last_name` 
from `deliverables` 
inner join `users` on `users`.`id` = `deliverables`.`user_id` 
where `deliverables`.`specialty_id` = '11' and 
      `deliverables`.`role_id` <> '1'

输出为:

file_code  file_name       dedicated_hours

0001asder  test-file.docx  4
0001as234w asdf.doc        2
jgfjh2546  test.docx       4
0001asder  test-file.docx  1
0001asder  test-file.docx  0
0001asder  test-file.docx  0

我需要对文件代码相等的专用\u小时进行求和,因此应该如下所示:

file_code  file_name       dedicated_hours  sum

0001asder  test-file.docx  4                5
0001as234w asdf.doc        2                2
jgfjh2546  test.docx       4                4
0001asder  test-file.docx  1                5
0001asder  test-file.docx  0                5
0001asder  test-file.docx  0                5

im使用sum(专用\u小时)和group by file \u代码,但它只显示:

file_code  file_name       dedicated_hours  sum

0001asder  test-file.docx  4                5
0001as234w asdf.doc        2                2
jgfjh2546  test.docx       4                4

如何同时计算和显示所有注册表?

oogrdqng

oogrdqng1#

你的mysql版本(5.0.12)不支持窗口功能(升级到最新版本应该是一个不错的奖励:)
不过,我们可以使用派生表来确定聚合的 SUM() 为了一个 file_code 分开。然后,我们可以简单地连接回主表,以显示sum列。

SELECT 
  d.file_code,
  d.file_name, 
  d.dedicated_hours,  
  dt.sum, 
  u.first_name, 
  u.last_name 
FROM deliverables AS d 
JOIN users AS u 
  ON u.id = d.user_id 
JOIN
(
  SELECT file_code, 
         SUM(dedicated_hours) AS sum 
   WHERE speciality_id = '11' AND 
         role_id <> '1'
   GROUP BY file_code
) AS dt 
  ON dt.file_code = d.file_code
WHERE d.speciality_id = '11' AND 
      d.role_id <> '1'

MySQL8.0.2及更高版本的解决方案只需使用 SUM(..) OVER (..) ```
SELECT
d.file_code,
d.file_name,
d.dedicated_hours,
SUM(d.dedicated_hours) OVER (PARTITION BY d.file_code) AS sum,
u.first_name,
u.last_name
FROM deliverables AS d
JOIN users AS u
ON u.id = d.user_id
WHERE d.speciality_id = '11' AND
d.role_id <> '1'

相关问题