简体   繁体   English

MYSQL查询SUM和DISTINCT?

[英]MYSQL Query for SUM and DISTINCT?

I have a database with the first five columns like this: 我有一个带有前五列的数据库,如下所示:

ID  NAME  QUANTITY   PRICE   KIND
1    Dog       2       5      A
2    Cat       1       6      B
3    Dog       2       5      C
4    Bird      5       5      C

(DOG QUANTITY and PRICE will always be the same) (DOG QUANTITY和PRICE将始终相同)

What I want to do to is to something like 我想做的是像

SELECT KIND, SUM(QUANTITY * PRICE) GROUP BY KIND WHERE DISTINCT NAME 按种类不同的名称选择种类,总和(数量*价格)

So that I get something that looks like this: 这样我得到的东西看起来像这样:

A 10
B  6
C 25

(The duplicate DOG is eliminated.) (消除了重复的DOG。)

I know my syntax above is grossly wrong -- it's just seems to be the most eloquent way of explaining what sort of thing I'm looking for. 我知道上面的语法是完全错误的-这似乎只是解释我要寻找的东西的最雄辩的方式。

In other words, I want to get rid of non-distinct NAMES then SUM the rest. 换句话说,我想摆脱不明显的名称,然后求和其余的。 I seem to be able to do one or the other but not both. 我似乎能够做到其中之一,但不能两者兼而有之。

Any ideas? 有任何想法吗? If worse comes to worst I can do it as a loop in PHP rather than as a single MYSQL query. 如果更糟的是,我可以将其作为PHP中的循环而不是单个MYSQL查询来实现。

I'm not really clear about either what the rules are or why your table is in that format (with repeated name, quantity,price) but here is one way of getting your expected output. 我不清楚规则是什么,还是表为什么是这种格式(具有重复的名称,数量,价格),但我不清楚,但这是获得期望输出的一种方法。

select kind, SUM(quantity*price)
from
(
SELECT name, quantity, price, min(kind) kind
FROM YourTable
group by name, quantity, price
) t
group by kind

Here I chose the item with the lowest ID as the one to keep: 在这里,我选择ID最低的项作为保留项:

Select T.Kind, Sum( T.Quantity * T.Price ) As Total
From Table As T
Where Id = (
            Select Min(T2.Id)
            From Table As T2
            Where T2.Name = T.Name
            )
Group By T.Kind

Assuming that your table is unique on Name and Kind, you can do: 假设您的表在“名称”和“种类”上是唯一的,则可以执行以下操作:

Select T.Kind, Sum( T.Quantity * T.Price ) As Total
From Table As T
Where T.Kind =  (
                Select Min(T2.Kind)
                From Table As T2
                Where T2.Name = T.Name
                )
Group By T.Kind

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

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