简体   繁体   中英

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

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.

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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