如何将查询结果转换为每一行的计数汇总

时间:2019-06-12 07:29:02

标签: sql sql-server

这是查询的结果:

      LNAME   |    LISTAGG
--------------+---------------
              | ALEX
 BAIRSTOW     |
 BROAD        | STUART
 BUTLER       |
 COOK         | ALAISTER,ALEX
 HALES        | ALEX
 JENNINGS     |
--------------+---------------
(7 rows)

我想将结果设为0、1或该行中的条目数,例如(ALAISTER,ALEX)为2且为空格式。

所以输出应该像:

  LNAME   |    LFNAME     | LNAME_COUNT  | LFNAME_COUNT
----------+---------------+--------------+-------------
 BROAD    | STUART        | 1            |   1
 BAIRSTOW |               | 1            |   0
 COOK     | ALAISTER,ALEX | 1            |   2
          | ALEX          | empty        |   1
 JENNINGS |               | 1            |   empty
 HALES    | ALEX          | 1            |   1
 BUTLER   |               | 1            |   0
----------+---------------+--------------+-------------
(7 rows)

我使用了一个case表达式,但是不能中断(ALAISTER,ALEX)部分。

2 个答案:

答案 0 :(得分:0)

在SQL Server中,您可以使用 click_whatsapp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isAppInstalled()) openWhatsApp(); else showMessage("Whatsapp is not install"); } }); 进行此操作。

LEN()

Demo on db<>fiddle for SQL Server

如果您的DBMS是MySQL,只需将SELECT LNAME, LISTAGG AS LFNAME, CASE WHEN LNAME IS NULL THEN CAST(0 AS VARCHAR (5)) WHEN LEN(LNAME) > 1 THEN CAST((LEN(LNAME) - LEN(REPLACE(LNAME, ',', ''))) + 1 AS VARCHAR (5)) ELSE 'empty' END AS LNAME_COUNT, CASE WHEN LISTAGG IS NULL THEN CAST(0 AS VARCHAR (5)) WHEN LEN(LISTAGG) > 1 THEN CAST((LEN(LISTAGG) - LEN(REPLACE(LISTAGG, ',', ''))) + 1 AS VARCHAR (5)) ELSE 'empty' END AS LFNAME_COUNT FROM TableName 更改为LEN()

答案 1 :(得分:0)

以下查询将满足您的需求

     Declare @table table ( lname  varchar (20),   listagg varchar (20));

insert into @table ( lname , listagg ) values
(''        , 'alex'),
('bairstow', null),
('broad'   , 'stuart'),
('butler'  , ''),
('cook'    , 'alaister,alex'),
('hales'   , 'alex'),
('jennings', null);

 select 
  lname,
  listagg as LFName,
  case when lname <>'' then len(lname)-len(replace(lname,',',''))+1 else 0 end as LName_count,
  case when listagg <>'' then len(listagg)-len(replace(listagg,',',''))+1 else 0 end  as LFName_count
  from @table