[英]How do I select this grouped data correctly?
First of all, sorry for the generic title, I don't know how exactly to word the question I have.首先,对于通用标题,我不知道如何准确地表达我的问题。
I am working with a legacy database and can't make changes to the schema, so I'm forced to work with what I've got.我正在使用旧数据库并且无法更改架构,所以我不得不使用我所拥有的。
Table setup (columns):表设置(列):
Example data:示例数据:
UniqueId Status Count
679FCE83-B245-E511-A42C-90B11C2CD708 completed 64
679FCE83-B245-E511-A42C-90B11C2CD708 Attention 1
679FCE83-B245-E511-A42C-90B11C2CD708 failed 101
4500990D-F516-E411-BB09-90B11C2CD708 completed 100
4500990D-F516-E411-BB09-90B11C2CD708 Attention 17
4500990D-F516-E411-BB09-90B11C2CD708 failed 516
557857BD-6B46-E511-A42C-90B11C2CD708 completed 67
557857BD-6B46-E511-A42C-90B11C2CD708 Attention 4
557857BD-6B46-E511-A42C-90B11C2CD708 failed 103
What I am trying to do is select all of the records, grouped by uniqueId, with a separate column for each of the status's containing their individual counts.我要做的是 select 所有记录,按 uniqueId 分组,每个状态都有一个单独的列,其中包含各自的计数。 The results would look something like this...
结果看起来像这样......
UniqueId, count(completed), count(failed), count(Attention)
679FCE83-B245-E511-A42C-90B11C2CD708 64 101 1
4500990D-F516-E411-BB09-90B11C2CD708 100 516 17
557857BD-6B46-E511-A42C-90B11C2CD708 67 103 4
I'm sure I'm missing something basic with this, but I can't seem to find the words to Google my way out of this one.我确定我错过了一些基本的东西,但我似乎无法找到谷歌的话。
Could someone push me in the right direction?有人能把我推向正确的方向吗?
You can use conditional aggregation:您可以使用条件聚合:
select uniqueid,
sum(case when status = 'Completed' then count else 0 end) as completed,
sum(case when status = 'Failed' then count else 0 end) as failed,
sum(case when status = 'Attention' then count else 0 end) as attention
from t
group by uniqueid;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.