SQL-计入多列 [英] Sql - count into multiple columns

查看:84
本文介绍了SQL-计入多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的表:

 num | type
-----+------
 123 | 3
 123 | 2
 123 | 3
 123 | 2
 124 | 3
 124 | 1
 124 | 3
 124 | 3

我想按num列分组,并有一个列计算每种不同的类型(我事先知道这里所有可能的值).所以我会得到:

I want to group by the num column, and have a column counting each distinct type (I know all the possible values here in advance). So I would get:

 num | 1 | 2 | 3
-----+---+---+---
 123 | 0 | 2 | 2
 124 | 1 | 0 | 3

SQL可能吗?我正在使用MySql.

Is this possible with SQL? I am using MySql.

推荐答案

SELECT `num`,
    SUM(type = 1) as `1`, 
    SUM(type = 2) as `2`, 
    SUM(type = 3) as `3`
FROM `your_table`
GROUP BY `num`

这篇关于SQL-计入多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆