如何在SQL中将多行合并为一行

时间:2019-05-02 05:43:33

标签: sql-server

我想查找一个公司中员工的总数,以及在一个查询中有多少名女性和男性工程师。

当这是我的查询所要查找的唯一内容时,我就可以只获取一行中所有同伙的总和,但是,一旦我尝试将其与查询中的查询相结合,就可以得出男性和女性的数量,副职称开始分开。

我当前的代码如下:

SELECT
    count(*) as [Number of Employees], Gender, Job
FROM 
    @table
WHERE 
    Job like '%Associate%'
GROUP BY grouping sets
    ((Job), (Gender))

每种类型的关联作业的结果集都有一行,我试图弄清楚如何将它们以“ associate”的名称组合在一行下

4 个答案:

答案 0 :(得分:0)

添加此内容:

SELECT 
    count(*) as [Number of Employees],
    Gender, 
    JobTitle 
FROM 
    HumanResources.Employee 
WHERE 
    JobTitle like '%Engineer%' 
Group by grouping sets
    ((JobTitle), (Gender)) 
HAVING 
    COUNT(*)>=3

答案 1 :(得分:0)

好吧,随您便 您可以尝试此操作,因为

SELECT SUM(a.[Number of Employees]) AS Value1, a.Gender , a.JobGroup FROM (
SELECT 'Engineer' AS JobGroup, COUNT(*) AS [Number of Employees], Gender, JobTitle FROM HumanResources.Employee WHERE JobTitle LIKE '%Engineer%' GROUP BY grouping sets ((JobTitle), (Gender))) a
GROUP BY a.Gender,a.JobGroup

答案 2 :(得分:0)

检查此脚本。此外,这还将在F&M的“职务标题”列中返回“ Engineer”值。但是,如果您要求在那里具有NULL,则脚本中需要进行一些调整。

注意:子查询只是为了更好地理解。这也可以通过单个查询来实现。

SELECT COUNT(*),
GENDER,
JobTitle 
FROM
(    
    SELECT 
    JobTitle,
    Gender, 
    CASE 
        WHEN JobTitle like '%Engineer%' THEN 'Engineer'
        ELSE JobTitle
    END AS JobTitle
    FROM HumanResources.EmployeeFROM 
)A
WHERE A.JobTitle = 'Engineer' 
GROUP BY GENDER,JobTitle

答案 3 :(得分:0)

这是简单的方法

#define WHITELIST_DEVICE {                                  \
                      {0x45,0x11,0xDF,0xED,0x2B,0x61},  \
                      {0xAB,0x11,0xDF,0x61,0x6B,0x2B},  \
                      {0x61,0x6B,0x3B,0xED,0x61,0x61},  \
                      {0xDF,0x55,0xDF,0x6B,0x6B,0x61},  \
                     } /**< List of device mac addresses in whitelist*/

输出

SELECT SUM(numberofemployees) AS total,
    Gender,
    CASE WHEN JobTitle LIKE '%Engineer%' THEN 'Engineer' ELSE JobTitle END AS JobTitle
FROM @table
GROUP BY Gender,
    CASE WHEN JobTitle LIKE '%Engineer%' THEN 'Engineer' ELSE JobTitle END