表:我在SQL Server 2012中有一个数据库表TestingTable。这就是表的样子:
column_ts column1 FirstName LastName
2016-09-30 00:04:00.000 5 Martha Stuart
2016-09-30 00:24:00.000 51 Tom Riddle
2016-09-30 00:29:00.000 32 Harry Potter
2016-09-30 00:44:00.000 128 Anderson Smith
2016-09-30 00:48:00.000 23 Lisa Young
2016-09-30 01:04:00.000 88 Mad Max
2016-09-30 01:59:00.000 46 Sam King
DDL :您可以使用以下方式创建此表:
CREATE TABLE TestingTable
(
column_ts datetime,
column1 int,
FirstName varchar(255),
LastName varchar(255)
);
INSERT INTO TestingTable
VALUES ('2016-09-30 00:04:00.000',5,'Martha','Stuart'),
('2016-09-30 00:24:00.000',51,'Tom','Riddle'),
('2016-09-30 00:29:00.000',32,'Harry','Potter'),
('2016-09-30 00:44:00.000',128,'Anderson','Smith'),
('2016-09-30 00:48:00.000',23,'Lisa','Young'),
('2016-09-30 01:04:00.000',88,'Mad','Max'),
('2016-09-30 01:04:00.000',46,'Sam','King');
我有一个查询,只有当column_ts的分钟值在26-30或56-00之间时才会选择column1。
select ISNULL(column1,0) from TestingTable
where ((DATEPART(n, column_ts) > 25) AND DATEPART(n, column_ts) <= 30)
OR (((DATEPART(n, column_ts) > 55) AND DATEPART(n, column_ts) <= 59) OR DATEPART(n, column_ts) = 0);
结果将是:
(No column name)
32
46
我的目标:现在我想将上述查询用作子查询。当给出FirstName(将具有唯一值)时,选择具有该名称的行,但仅当column_ts具有26-30或56-00之间的分钟值时才选择column1的值。否则,将column1选为零。
我尝试了什么:我想我必须使用CASE,但我读到我们不能/不应该在CASE中使用括号。我尝试了一些但却出现语法错误:
select column_ts, column1 =
CASE column_ts
WHEN (((DATEPART(n, column_ts) > 25) AND DATEPART(n, column_ts) <= 30)
OR (((DATEPART(n, column_ts) > 55) AND DATEPART(n, column_ts) <= 59) OR DATEPART(n, column_ts) = 0)) THEN column_ts
ELSE 0
END, FirstName, LastName
from TestingTable
where FirstName = 'Tom';
错误:以上查询会出现语法错误:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '>'.
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near 'DATEPART'.
请建议我如何更正上述查询或编写其他查询以实现我的目标。
答案 0 :(得分:1)
尝试使用以下查询。
SELECT column_ts,
column1 =
CASE
WHEN (((DATEPART(n, column_ts) > 25) AND DATEPART(n, column_ts) <= 30)
OR (((DATEPART(n, column_ts) > 55) AND DATEPART(n, column_ts) <= 59) OR DATEPART(n, column_ts) = 0)) THEN column1
ELSE 0
END, FirstName, LastName
FROM TestingTable
WHERE FirstName = 'Tom';
答案 1 :(得分:0)
此?
select
column1,
DATEPART(n, column_ts) as MyDatePart
,
[Column1OrBust] =
case
when (DATEPART(n, column_ts) > 25 AND DATEPART(n, column_ts) <= 30) OR ( DATEPART(n, column_ts) > 55 AND DATEPART(n, column_ts) <= 59 ) then column1
else 0
end
, FirstName, LastName
from TestingTable