SQL GROUP BY,其中包含镜像值的列

编程入门 行业动态 更新时间:2024-10-28 08:21:48
本文介绍了SQL GROUP BY,其中包含镜像值的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

对不起的标题。我无法想出一个更好的方式来描述我的问题。

我有下表:

Category | A | B A | 1 | 2 A | 2 | 1 B | 3 | 4 B | 4 | 3

我想按类别,每个类别只返回1行,但同时提供列的值 A 和 B 。

所以结果应该如下所示:

category | resultA | resultB A | 1 | 2 B | 4 | 3

这是如何实现的?

我试过这个语句:

SELECT类别,a,b FROM表格 GROUP BY类别

但很明显,我收到以下错误:

列a在选择列表中无效,因为它在集合函数或GROUP BY子句中不包含。

列b在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

我怎样才能达到预期的效果?

>试试这个:

SELECT类别,MIN(a)AS resultA,MAX(a)AS resultB FROM表格 GROUP BY类别

如果这些值是镜像的,那么您可以使用 a 之类的单个列上应用c $ c> MIN , MAX p>

Sorry for the bad title. I couldn't think of a better way to describe my issue.

I have the following table:

Category | A | B A | 1 | 2 A | 2 | 1 B | 3 | 4 B | 4 | 3

I would like to group the data by Category, return only 1 line per category, but provide both values of columns A and B.

So the result should look like this:

category | resultA | resultB A | 1 | 2 B | 4 | 3

How can this be achieved?

I tried this statement:

SELECT category, a, b FROM table GROUP BY category

but obviously, I get the following errors:

Column 'a' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Column 'b' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

How can I achieve the desired result?

解决方案

Try this:

SELECT category, MIN(a) AS resultA, MAX(a) AS resultB FROM table GROUP BY category

If the values are mirrored then you can get both values using MIN, MAX applied on a single column like a.

更多推荐

SQL GROUP BY,其中包含镜像值的列

本文发布于:2023-10-14 11:29:42,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:镜像   其中包含   SQL   GROUP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!