我希望从一列中选择并计算不同的天数,并排除在另一列中具有特定值的那些天。
表结构是这样的
+-------------------------+-------------------------+
| DAY | CHECK |
+-------------------------+-------------------------+
| 2018-07-18 00:00:00.000 | 2018-07-18 12:46:35.000 |
| 2018-07-19 00:00:00.000 | 2018-07-19 15:58:14.000 |
| 2018-07-20 00:00:00.000 | 2018-07-20 15:52:57.000 |
| 2018-07-21 00:00:00.000 | 2018-07-21 00:00:00.000 |
| 2018-07-23 00:00:00.000 | 2018-07-23 08:54:49.000 |
| 2018-07-23 00:00:00.000 | 2018-07-23 12:52:41.000 |
| 2018-07-26 00:00:00.000 | 2018-07-26 08:55:34.000 |
+-------------------------+-------------------------+
因此,预期结果将是DAY列中不同天的计数,并且该计数排除了CHECK列中该时间为00:00:00.000的所有日期。
在这种情况下,计数结果将为5天
我设法计算了天数,但是还没有弄清楚检查栏的条件部分
COUNT(DISTINCT DAY) AS 'TotalDays',
答案 0 :(得分:0)
您可以使用GROUP BY
,然后使用HAVING
子句实施检查:
declare @tmp table ([day] datetime , [check] datetime)
insert into @tmp values
('2018-07-18 00:00:00.000','2018-07-18 12:46:35.000')
,('2018-07-19 00:00:00.000','2018-07-19 15:58:14.000')
,('2018-07-20 00:00:00.000','2018-07-20 15:52:57.000')
,('2018-07-21 00:00:00.000','2018-07-21 00:00:00.000')
,('2018-07-23 00:00:00.000','2018-07-23 08:54:49.000')
,('2018-07-23 00:00:00.000','2018-07-23 12:52:41.000')
,('2018-07-26 00:00:00.000','2018-07-26 08:55:34.000')
select [DAY]
from @tmp
group by [DAY]
having min(cast ([check] as time)) <> '00:00:00.0000000'
结果:
由于需要计数,因此可以用另一个选择包装语句:
select count(*) as TotalDays
from
(
select [DAY]
from @tmp
group by [DAY]
having min(cast ([check] as time)) <> '00:00:00.0000000'
) T
结果:
答案 1 :(得分:0)
如何?
SELECT COUNT(DISTINCT [DAY]) AS 'TotalDays'
FROM tbl
WHERE [CHECK] <> DATEADD(day, DATEDIFF(day, 0, [CHECK]), 0);
查看示例数据,也许WHERE [CHECK] <> [DAY]
的WHERE子句就足够了。