简体   繁体   English

对查询结果进行分组以获取此格式

[英]Group a query result to get this format

I have the following schema: 我有以下架构:

a VARCHAR(255),
b INTEGER,
c INTEGER,
d TEXT

In my database, if d is not null, then c is 0. What I would like to do is group all columns that have equal a s and equal b s. 在我的数据库中,如果d不为空,则c为0。我想这样做的是组具有相同的所有列a S和等于b秒。 However, I'd like to use the sum of c for the result and the non-null value of d (if there is one). 但是,我想使用c的总和作为结果以及d的非空值(如果有的话)。 For instance, if my data looked like this: 例如,如果我的数据如下所示:

"XXX" 100 1 NULL
"XXX" 100 1 "my text"
"YYY" 5 1 NULL
"YYY" 7 0 "other text"

I would like the result to be: 我希望结果是:

"XXX" 100 2 "my text"
"YYY" 5 1 NULL
"YYY" 7 0 "other text"

Is there a query I can use that will do this? 我可以使用一个查询来做到这一点吗?

You can use group_concat to concatenate the values of column d into one field 您可以使用group_concat将d列的值连接到一个字段中

SELECT a, b, SUM(c), GROUP_CONCAT(d)
FROM table
GROUP BY a, b
ORDER BY a asc, b asc

If you have two rows like 如果你有两行像

"XXX", 100, 0, "Some Text"
"XXX", 100, 0, "Some More Text"

This will return 这将返回

"XXX", 100, 0, "Some Text,Some More Text"

However if you have three rows: 但是,如果您有三行:

"XXX", 100, 0, "Some Text"
"XXX", 100, 0, "Some More Text"
"XXX", 100, 1, NULL

You will get 你会得到

"XXX", 100, 1, "Some Text,Some More Text"

(ie, the null will disappear. Use coalesce if you need to maintain a placeholder) (即,空值将消失。如果需要维护占位符,请合并使用)

I would do this just using max() : 我只是使用max()来做到这一点:

select a, b, sum(c) as c, max(d) as d
from table t
group by a, b;

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

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