---
title: "【别点进来，垃圾】mysql的一种 条件查询 when case"
author: "cheer_nice"
date: "2011-05-11T16:08:51Z"
tags: []
categories: ["数据库"]
slug: "mysql-when-case"
draft: false
lastmod: "2011-05-11T16:08:51Z"
id: 1040118
url: "https://cheer-nice.iteye.com/blog/1040118"
---

背景

mysql 查询问题

说有这样一个表

uid gid type

 1   1   2

 1   2   1

 2   1   3

 2   2   2

 3   1   1

 3   2   3  

uid 是user 的ID  gid是游戏的ID type是获得的名次

然后想搞一个查询 结果形如这样

 

uid  金牌数  银牌数 铜牌数

 

每一个user一个行

 

```
select uid, sum(case when `medalstype`=1  then 1 else 0 end) '金', sum(case when `medalstype`=2  then 1 else 0 end)  '银'
, sum(case when `medalstype`=3  then 1 else 0 end) '铜' from jrun_gamesmedals group by uid;

 
```

 case  when嗯嗯 强大