简体   繁体   English

根据计数组合行,添加值

[英]Combing rows based on a count, adding values

Here's the dilemma: I have a table with rows. 这是一个难题:我有一个带有行的表。 I need to count based on frequency of a certain value (in the eMail column), and then ADD numbers in certain column (cost)... as an example 我需要根据某个值的频率(在eMail列中)进行计数,然后在某些列(费用)中添加数字...例如

mail           cost
me@me.com      10
me@me.com      5
john@john.com  3
me@me.com      7
john@john.com  2

So I need to group rows based on the email address, and add the numbers in the grouped rows "cost" column. 因此,我需要根据电子邮件地址对行进行分组,并在分组的行“费用”列中添加数字。 The results should come out as an array: 结果应以数组形式出现:

email          frequency  totalCost
me@me.com      3          22
john@john.com  2          5

Here's one way to try: 这是尝试的一种方法:

INSERT INTO frequency (mail, frequency, cost)
SELECT mail, COUNT(*), SUM(cost) FROM mail GROUP BY mail;

This assumes: 假设:

mail is a table containing your first data set frequency is the table you wish to enter your aggregate values. mail是一个包含您的第一个数据集的表格。 frequency是您希望输入汇总值的表格。

Let us know if this works :) 让我们知道这是否有效:)

[edit/additional]: These are the table definitions I assumed: [编辑/附加]:这些是我假设的表定义:

CREATE TABLE mail (
      mail VARCHAR(50)
    , cost INT
);

CREATE TABLE frequency (
      mail VARCHAR(50)
    , frequency INT
    , cost INT
);

This query should work: 此查询应工作:

SELECT email, COUNT(*) AS frequency, SUM(cost) AS totalCost
FROM your_table
GROUP BY email

Then, you fetch it in PHP with whatever API you use. 然后,使用任何使用的API在PHP中获取它。 These are basics, in theory you should be able to come up with those solutions on your own if you are ready to make an application. 这些都是基础知识,理论上,如果您准备提出申请,那么您应该能够自己提出这些解决方案。

This can be done with a single SQL query. 这可以通过单个SQL查询来完成。

SELECT
    email,
    COUNT(email) AS frequency,
    SUM(cost) AS totalCost
FROM
    emails
GROUP BY
    email

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM