需要每个值类型的行数

时间:2016-10-03 12:09:04

标签: mysql sql group-by case where

我有格式的表格

SID LinkName           
A1  Link1           
A1  Link2           
A2  Link1           
A2  Link2          
A2  Link3         
A3  Link2
A1  Link1
A2  Link2

我需要以下面的格式显示每种链接类型的计数结果

Link1   Link2   Link3                   
 3        4        1

请告知。

编辑: 此外,如果我需要以下面的格式显示每种链接类型的不同计数的结果。像A1 - > Link1出现两次,但只需要计算一次

Link1   Link2   Link3                   
 2        3        1

4 个答案:

答案 0 :(得分:2)

在MySQL中,您可以这样做:

select sum(linkname = 'link1') as link1,
       sum(linkname = 'link2') as link2,
       sum(linkname = 'link3') as link3
from t;

编辑:

如果您想要计算不同的sid

select count(distinct case when linkname = 'link1' then sid end) as link1,
       count(distinct case when linkname = 'link2' then sid end) as link2,
       count(distinct case when linkname = 'link3' then sid end) as link3
from t;

答案 1 :(得分:1)

select sum(case when LinkName = 'Link1' then 1 end) as link1,
       sum(case when LinkName = 'Link2' then 1 end) as link2,
       sum(case when LinkName = 'Link3' then 1 end) as link3
from tablename

答案 2 :(得分:0)

通常,您不会将这些放在列中,而是放在行中:

select LinkName, count(LinkName) as LinkCount
from table group by LinkName

......会给出:

LinkName | LinkCount
Link1    | 2
Link2    | 3
Link3    | 1

这样,如果出现新的链接类型,那就没什么大不了的。这会起作用,还是必须在列中?如果是这样,你可能会查看单个计数(*)和两个子选择或一个相当复杂的自连接或某些案例方法。像:

select count(*) as Link1, (select count(*) from table where LinkName='Link2') as Link2...
from table where LinkName='Link1'

......或类似的东西。

答案 3 :(得分:0)

select Link1,Link2,Link3
from 
(
 select Id,Rtrim(Ltrim(Name)) as Name
 from Table_1
) src
pivot
(
  count(Id)
for Name in (Link1,Link2,Link3)
) piv;

给出:

Link1   Link2   Link3
4        3      1