简体   繁体   English

DB2 SQL分为多列

[英]DB2 SQL count into multiple columns

i have a situation similar to this: Sql - count into multiple columns 我有类似的情况: SQL-数入多列

i'll break it down again here 我会在这里再次分解

i have a table with these values: 我有一个表,这些值:

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

i want to group by the num column, and have a column counting each distinct type. 我想按num列分组,并有一个列来计数每种不同的类型。 so i would get: 所以我会得到:

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

the top solution on that question was: 该问题的最佳解决方案是:

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

when i try this, i get an error saying 当我尝试这个时,我得到一个错误提示

An unexpected token "=" was found following "LECT NUM, SUM(type". Expected tokens may include: "CONCAT". SQLSTATE=42601 在“ LECT NUM,SUM(type)”之后发现意外的标记“ =”。预期的标记可能包括:“ CONCAT”。SQLSTATE = 42601

can somebody point me towards a workable sql query for db2? 有人可以指出我对db2可行的sql查询吗?

The syntax in the other answer was for MySQL, you should try the following which uses the CASE syntax: 另一个答案中的语法是针对MySQL的,您应该尝试以下使用CASE语法的语法:

select num,
  sum(case when type = 1 then 1 else 0 end) Type1,
  sum(case when type = 2 then 1 else 0 end) Type2,
  sum(case when type = 3 then 1 else 0 end) Type3
from yourtable
group by num

See SQL Fiddle with Demo (SQL Server demo) 请参见带有演示的SQL Fiddle (SQL Server演示)

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

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