用于根据布尔列

时间:2016-10-17 20:23:51

标签: sql sql-server

我正在尝试基于布尔列

合并数据

原始数据:

FName LName Status
------------------
x     y     1
x     y     0
a     b     1
t     t     1
u     e     1
t     t     1
a     b     0

最终结果我想实现

FName LName Yes  No
-------------------
x     y     1    1
a     b     1    1
t     t     2    0
u     e     1    0

这就是我尝试的但却没有得到我想要的东西 -

SELECT
    [FirstName], [LastName], COUNT(*) AS No
FROM 
    [dbo].[tablename]  
GROUP BY
    [FirstName], [LastName], [Status] 
HAVING
    COUNT(*) > 1 AND Status = 0 

UNION  

SELECT 
    [FirstName], [LastName], COUNT(*) AS Yes
FROM 
    [dbo].[tablename]  
GROUP BY
    [FirstName], [LastName], [Status] 
HAVING
    COUNT(*) > 1 AND Status = 1

我相信必须有一种简单的方法来实现这个目标

2 个答案:

答案 0 :(得分:0)

您只需要SUMCASE表达式:

SELECT  FName,
        LName,
        SUM(CASE WHEN [Status] = 1 THEN 1 ELSE 0 END) Yes,
        SUM(CASE WHEN [Status] = 0 THEN 1 ELSE 0 END) No
FROM YourTable
GROUP BY FName,
         LName;

答案 1 :(得分:0)

可能的方法是

select [FirstName],[LastName], 
   sum(0+[Status]) as Yes,
   count([Status]) - sum(0+[Status]) as No
from [dbo].[tablename]  
group by [FirstName],[LastName]

0+[Status]隐式将bit [Status]转换为整数。