简体   繁体   English

Pivot sql output - Google sql 面试问题

[英]Pivot sql output - Google sql Interview question

I have asked to query a table to return the names of the student that starts with A along with their count.我已要求查询一个表以返回以 A 开头的学生的姓名及其计数。 Let us table has "Alan" and "Adam" entry.让我们表有“Alan”和“Adam”条目。 The output should be 2, Alan, Adam. output 应该是 2,Alan,Adam。

You can use left() , and string_agg() .您可以使用left()string_agg()

Option 1: which you have asked for.选项1:您要求的。

select
    count(firstChar) as totalCount,
    string_agg(fname, ', ') as allNames
from
(
    select 
        fname,
        left(fname, 1) as firstChar
    from myName
) res
group by
   firstChar

Output: DEMO Output:演示

*----------------------*
|totalcount | allnames |
*----------------------*
|   2       |Adam, Alan|
*----------------------*

Option 2:选项 2:

select 
    left(fname, 1) as firstChar, 
    count(left(fname, 1)) as total
from myName
group by
    left(fname, 1)

Output: DEMO Output:演示

*-------------------*
|firstChar  | count |
*-------------------*
|   A       |    2  |
*-------------------*

You can use left() with window function:您可以将left()与 window function 一起使用:

select name, count(*) over ()
from table t
where left(fname, 1) = 'a';

Edit: Use string_agg() to concat strings into single row:编辑:使用string_agg()将字符串连接成单行:

select count(*), string_agg(fname, ', ')
from table t
where left(fname, 1) = 'a';

In BigQuery, I would use array_agg() :在 BigQuery 中,我会使用array_agg()

select count(*), array_agg(name)
from t
where name like 'A%';

Please find Answer as per your output: I have created a table below:请根据您的 output 找到答案:我在下面创建了一个表格:

Create table dbo.test_table (FNAME varchar(50));

insert into dbo.test_table(FNAME) values
('Alan'),
('Adam')
         

Query for the output:查询 output:

with CTE AS (
SELECT
    COUNT(*) as total_Count,
    string_agg(fname, ', ') as First_Names
FROM dbo.test_table
WHERE LEFT(FNAME,1)='A'
  )
  SELECT CONCAT(total_Count,',', First_Names) As output FROM CTE

在此处输入图像描述

SQL Fiddle Link for output: SQLFiddle SQL Fiddle链接: SQLFiddle

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

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