我的表应如下所示:
slno sheetno time_stamp
1 101 2018-05-27 11:16:58
2 103 2018-05-27 11:20:18
3 102 2018-05-27 11:24:39
4 105 2018-05-27 11:27:44
5 106 2018-05-27 11:34:03
6 107 2018-05-27 11:51:32
7 108 2018-05-27 12:41:34
8 109 2018-05-27 12:48:13
9 110 2018-05-27 12:52:40
10 111 2018-05-27 13:18:59
11 112 2018-05-27 14:13:07
12 113 2018-05-27 14:18:04
13 114 2018-05-27 14:21:12
14 115 2018-05-27 14:54:01
15 117 2018-05-27 14:55:14
16 118 2018-05-27 14:57:31
17 119 2018-05-27 15:05:30
18 120 2018-05-27 15:30:44
19 121 2018-05-27 15:46:38
20 122 2018-05-27 16:02:16
21 123 2018-05-28 11:32:10
22 124 2018-05-28 11:38:18
23 125 2018-05-28 11:49:45
24 126 2018-05-28 11:52:09
25 127 2018-05-28 12:21:00
26 128 2018-05-28 12:24:33
27 129 2018-05-28 13:04:56
28 130 2018-05-28 14:10:07
29 140 2018-05-28 14:18:47
30 141 2018-05-28 14:22:09
31 142 2018-05-28 14:28:04
32 143 2018-05-28 14:37:53
33 144 2018-05-28 15:06:27
34 145 2018-05-28 15:33:05
35 146 2018-05-28 15:35:44
36 147 2018-05-28 15:53:41
37 148 2018-05-28 16:13:16
38 149 2018-05-28 16:27:51
39 150 2018-05-28 16:38:54
40 151 2018-05-28 16:44:54
我的输出应该是这样的:
From To Total No of days FN AN
27-05-2018 28-05-2018 2 2 2
这是我的查询:
SELECT
DATE_FORMAT(MIN(time_stamp), '%Y-%m-%d') AS min,
DATE_FORMAT(MAX(time_stamp), '%Y-%m-%d') AS max,
COUNT(DISTINCT DATE(time_stamp)) AS cnt,
COUNT(CASE WHEN TIME(time_stamp) < '12:00:00' THEN 1 END) AS FN,
COUNT(CASE WHEN TIME(time_stamp) >= '12:00:00' THEN 1 END) AS AN
FROM master_tab;
“ FN”,“ AN”的输出应分组。如何解决呢?
我试图将DISTINCT
放在显示我有价值的情况前面。
答案 0 :(得分:1)
您似乎在正确的轨道上:
SELECT
DATE_FORMAT(MIN(time_stamp), '%Y-%m-%d') AS min,
DATE_FORMAT(MAX(time_stamp), '%Y-%m-%d') AS max,
COUNT(DISTINCT DATE(time_stamp)) AS cnt,
COUNT(CASE WHEN TIME(time_stamp) < '12:00:00' THEN 1 END) AS FN,
COUNT(CASE WHEN TIME(time_stamp) >= '12:00:00' THEN 1 END) AS VA
FROM master_tab;
注意:
DATE_FORMAT
已经将这些值仅用作日期。DISTINCT
在MySQL中不是 一个函数,而是一个关键字FN
(上午)和VA
(晚上)时间的条件计数在存在匹配项时计数为1,否则计数NULL
。请注意,NULL
将忽略COUNT
,因此我们仅对记录进行匹配。 ELSE
条件(已省略)默认为NULL
。答案 1 :(得分:0)
您可以尝试以下查询:
SELECT
DATE_FORMAT(MIN(time_stamp), '%Y-%m-%d') AS min,
DATE_FORMAT(MAX(time_stamp), '%Y-%m-%d') AS max,
COUNT(DISTINCT DATE(time_stamp)) AS cnt,
COUNT(DISTINCT CONCAT(DATE(time_stamp),(CASE WHEN TIME(time_stamp) < '12:00:00' THEN 1 END))) AS FN,
COUNT(DISTINCT CONCAT(DATE(time_stamp),(CASE WHEN TIME(time_stamp) >= '12:00:00' THEN 1 END))) AS VA
FROM master_tab;
和输出
min max cnt FN VA
2018-05-27 2018-05-28 2 2 2