如何使用count()函数在SQL Server中检索单列作为两列?

时间:2018-07-31 05:45:55

标签: sql sql-server sql-server-2008

我有下表

ID          UserID      Email                           Status          Count
1           16          kiran.shahi@example.com         True            2
2           16          aibrahim@sbcglobal.net          False           3
3           16          russotto@icloud.com             False           3
4           16          seurat@optonline.net            False           3
5           16          paley@aol.com                   False           3
6           16          tmaek@aol.com                   False           3
7           16          baveja@verizon.net              False           3
8           16          wonderkid@mac.com               False           3
9           16          mkearl@live.com                 False           3
10          16          solomon@att.net                 False           3
11          16          enintend@gmail.com              False           3
12          16          rbarreira@outlook.com           False           3
13          16          pavel@yahoo.ca                  False           3
NULL        NULL        NULL                            NULL            NULL

然后执行存储过程

    @UserID INT
AS
BEGIN
    SET NOCOUNT ON;
    SELECT 
    @UserID AS UserID, 
    COUNT(T1.Status) AS Active, 
    COUNT(T2.Status) AS Inavtive 
    FROM UserStatus T1
    JOIN UserStatus T2
    ON T1.UserID = T2.UserID
    WHERE T1.Status = 1 AND T2.Status = 0 AND T2.UserID = @UserID  
END

返回哪个

    UserID      Active          Inavtive
1   16          12              12

我怎样才能达到结果

    UserID      Active          Inavtive
1   16          1               12 

3 个答案:

答案 0 :(得分:1)

请尝试使用COUNT而不是SUM。像这样

SELECT 
        @UserID AS UserID, 
        SUM(CASE WHEN Status = 1 THEN 1 ELSE 0 END) AS Active, 
        SUM(CASE WHEN Status = 0 THEN 1 ELSE 0 END) AS Inavtive 
    FROM UserStatus 
    WHERE 
    UserID = @UserID

答案 1 :(得分:1)

您可以按以下方式使用SUM:

SELECT 
    SUM(CASE WHEN Status =1 THEN 1 ELSE 0 end) as Active, 
    SUM(CASE WHEN Status =1 THEN 0 ELSE 1 end) as InActive 
FROM UserStatus 
    WHERE 
    UserID = @UserID 

答案 2 :(得分:0)

我尝试在count()而不是sum()函数中实现大小写,因为在没有sum()返回的记录的情况下,count()函数返回null我的代码中的计算。以下代码工作正常。在我的情况下,Status列必须为bit,以便满足我的条件并可以获得truefalse记录的计数。

@UserID INT
    AS
    BEGIN
        SET NOCOUNT ON;
        SELECT 
            @UserID AS UserID, 
            COUNT(CASE WHEN Status = 1 THEN ID END) AS Active, 
            COUNT(CASE WHEN Status = 0 THEN ID END) AS Inavtive 
        FROM UserStatus 
        WHERE 
        UserID = @UserID 
    END