Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 显示空值​大小写+总和_Sql_Sql Server 2008_Conditional_Case - Fatal编程技术网

Sql 显示空值​大小写+总和

Sql 显示空值​大小写+总和,sql,sql-server-2008,conditional,case,Sql,Sql Server 2008,Conditional,Case,我有一个具有以下结构的表: CREATE TABLE [dbo].[TESTING]( [ID] [nvarchar](2) NULL, [TYPE] [nvarchar] (1) NULL, [TIME] [int] NULL 以及以下数据: INSERT INTO [dbo].[TESTING] ([ID] ,[TYPE] ,[TIME]) VALUES ('A1','1',3), ('A1

我有一个具有以下结构的表:

CREATE TABLE [dbo].[TESTING](
    [ID] [nvarchar](2) NULL,
    [TYPE] [nvarchar] (1) NULL,
    [TIME] [int] NULL
以及以下数据:

INSERT INTO [dbo].[TESTING]
           ([ID]
           ,[TYPE]
           ,[TIME])
     VALUES
('A1','1',3),
('A1','1',6),
('A2','2',8),
('A2','2',9),
('B1','1',2),
('B1','1',6),
('B2','2',4),
('B2','2',8),
('B2','2',11),
('B2','2',12)
我想做的就是这样。我想创建一个列,如果时间大于5,它将接收值5

然后我提出以下声明:

select ID,  TYPE, 
(case when TIME <= 5 then '<= 5' 
when TIME > 5 then '> 5' 
else 'OTHER' end) AS CONDITION, 
SUM(TIME) TOTAL 
from [dbo].[TESTANDO] 
GROUP BY ID, TYPE,
(case when TIME <= 5 then '<= 5' 
when TIME > 5 then '> 5' 
else 'OTHER' end)
结果:

除了出现的数据之外,如果有值的话,我还想知道​​其中5个没有值​​我来的那条线总共是0。在本例中,组A2中没有符合条件的行使用交叉连接生成行,然后使用左连接和聚合填充值:

select i.id, i.type, c.condition, coalesce(sum(time), 0) as total
from (select distinct id, type from testing) i cross join
     (values ('<= 5'), ('> 5')) c(condition) left join
     testing t
     on t.id = i.id and
        t.type = i.type and
        ((condition = '<= 5' and time <= 5) or
         (condition = '> 5' and time > 5)
        )
group by i.id, i.type, c.condition
order by i.id, i.type, c.condition;

是一个DBFIDLE。

请在问题中以文本表的形式显示您想要的结果,并确保它们与您提供的数据相对应。已修改Gordon非常感谢!只有一件事,如果我想把一个地方,这是一个问题?喜欢其中类型=1@ClaytonTosatti . . . 将条件放入i的子查询中。