简体   繁体   English

用案例查询的MySQL总和输出另一个表

[英]MySql Sum with Case query to output another table

I have a table table1 like this. 我有一个这样的表table1。

    +---------+-------+
    | name    | Value | 
    +---------+-------+
    |       a | 1     | 
    |       b | 3     |
    |       a | 1     |
    |       d | 4     |
    |       c | 4     |
    |       d | 2     |
    +---------+-------+

I need to create another table which has a distinct name and the sum of values which whose names are the same from the previous table like this.. 我需要创建另一个表,该表具有不同的名称和值的总和,这些名称的名称与上一张表的名称相同,如下所示。

+---------+-------+
| name    | Value | 
+---------+-------+
|       a | 2     | 
|       b | 3     |
|       c | 4     |
|       d | 6     |
+---------+-------+

I have tried the query 我试过查询

SELECT Distinct t1.name, SUM (Case when t1.Name = t2.Name then t1.Value end) 
from table1 t1 join table1 t2 

which doesn't seem to work. 这似乎不起作用。

I am building a desktop application using c# to access these values in the output table, and I can easily obtain the desired result by simply using linq as opposed to the server side queries. 我正在使用c#构建一个桌面应用程序以访问输出表中的这些值,并且只需使用linq而不是服务器端查询,就可以轻松获得所需的结果。 Is it good practice to have the desktop application achieve this instead of creating the table in the database? 让桌面应用程序实现此目的而不是在数据库中创建表是一种好习惯吗?

You can simply try 你可以简单地尝试

select name, sum(Value)
from yourtable
group by name

Sql Fiddle Demo SQL小提琴演示

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

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