如何在SQL Server case语句中设置默认值?

时间:2017-02-06 15:34:10

标签: sql-server

我有一个喜欢显示状态和计数的方案。看下面的模型

Status            Counts
---------------   --------
Completed          10
In Progress         6
Others              0

我有这段代码:

SELECT 
    CASE 
       WHEN Status = 'I' THEN 'IN PROGRESS' 
       WHEN Status = 'O' THEN 'Others' 
       WHEN Status = 'C' THEN 'COMPLETED' 
    END AS ' Status', 
    COUNT(Status) AS ' Counts' 
FROM   
    table1

我的值仅为CompletedInProgress。目前我只获得两行。但我需要三行,包括Others,它的计数应为0 - 如何在SQL中执行此操作?

2 个答案:

答案 0 :(得分:3)

添加" else",如下所示:

SELECT CASE 
         WHEN Status= 'I' THEN 'IN PROGRESS' 
         WHEN Status= 'C' THEN 'COMPLETED' 
         ELSE 'Others' 
       END            AS ' Status'
FROM   table1

答案 1 :(得分:1)

根据我的理解,你有一个包含状态值的主表,我将简化为:

CREATE TABLE #MainTable
(
    id INT,
    [status] NVARCHAR(1)
)

您的问题是,如果O没有状态为Others的行,则在对行进行分组以获取计数时,您将无法获得0。< / p>

我建议你创建一个Status表来链接到RIGHT JOIN。这也将消除您对CASE陈述的需求。

完整解决方案:

CREATE TABLE #MainTable
    (
      id INT ,
      [status] NVARCHAR(1)
    );

INSERT  INTO #MainTable
        ( id, [status] )
VALUES  ( 1, 'I' ),
        ( 2, 'I' ),
        ( 3, 'I' ),
        ( 4, 'I' ),
        ( 5, 'C' ),
        ( 6, 'C' );

CREATE TABLE #status
    (
      [status] NVARCHAR(1) ,
      [statusText] NVARCHAR(15)
    );

INSERT  INTO #status
        ( status, statusText )
VALUES  ( 'I', 'In Progress' ),
        ( 'C', 'Completed' ),
        ( 'O', 'Others' );

SELECT  s.statusText ,
        COUNT(t.[status]) StatusCount
FROM    #MainTable t
        RIGHT JOIN #status s ON s.status = t.status
GROUP BY s.statusText;

DROP TABLE #MainTable;
DROP TABLE #status;

<强>产地:

statusText  StatusCount
Completed   2
In Progress 4
Others      0

在上面的示例中,它会加入I,O,C字符串值,我建议您使用ID值替换。然后你可以这样做:

CREATE TABLE #MainTable
    (
      id INT ,
      statusId INT
    );

CREATE TABLE #status
    (
      statusId INT ,
      statusShort NVARCHAR(1) ,
      statusText NVARCHAR(15)
    );

SELECT t.id ,
       t.statusId ,
       s.statusId ,
       s.statusShort ,
       s.statusText 
FROM #MainTable t
RIGHT JOIN #status s ON s.statusId = t.statusId

DROP TABLE #MainTable;
DROP TABLE #status;