在一个表中同时选择两个行

时间:2018-10-25 07:17:05

标签: php sql-server

我有这张桌子:

USERID  CHECKTIME                CHECKTYPE
1       2018-10-21 09:01:08.000  I
1       2018-10-21 10:00:51.000  I
1       2018-10-22 13:19:23.000  1
1       2018-10-22 15:56:11.000  0
1       2018-10-22 16:51:27.000  O

我需要选择两行,如下所示:

userid   in                         out
1        2018-10-22 13:19:23.000    2018-10-22 15:56:11.000   

但日期和用户ID相同 日期和用户名来自帖子页面php 数据库是与php的sqlserver连接

SELECT TOP 1 checktime, userid, checktype
FROM CHECKINOUT 
WHERE userid = '$idd' 
    AND CAST(checktime As DATE)='$x'
    AND checktype='1' 
UNION ALL
SELECT TOP 1 checktime, userid, checktype
FROM CHECKINOUT 
WHERE userid='$idd'
    AND CAST(checktime As DATE)='$x'
    AND checktype='0'

2 个答案:

答案 0 :(得分:0)

表结构

USERID:int(11)

CHECKTIME:日期时间

CHECKTYPE:char(2)

查询

SELECT USERID, MAX(`IN`) AS 'IN', MAX(`OUT`) AS 'OUT'
 FROM
(
    SELECT USERID
         , CASE WHEN CHECKTYPE = '1' THEN CHECKTIME ELSE '0000-00-00 00:00:00.000' END AS 'IN'
         , CASE WHEN CHECKTYPE = '0' THEN CHECKTIME ELSE '0000-00-00 00:00:00.000' END AS 'OUT'
    FROM CHECKINOUT
     WHERE CHECKTYPE IN ('0', '1')
) U
 GROUP BY U.USERID

我检查了本地地址,此查询效果很好。

说明

子查询U

它按CHECKTYPE条件收集IN和OUT的CHECKTIME。当没有IN数据时,默认值为“ 0000:00:00 ....”,而OUT也是。

在外部查询中

它将获得最大值(拒绝“ 0000:00:00 ...”)和组记录,因此我们可以获得正确的数据。

我建议使用GROUP BY而不是DISTINCT,因为它使Query的运行速度比DISTINCT快。

答案 1 :(得分:0)

你在这里

CREATE TABLE T
    ([UserId] int, [CheckDate] datetime, [CheckType] BIT)
;

INSERT INTO T
    ([UserId], [CheckDate], [CheckType])
VALUES
    (1, '2018-10-21 09:01:08', 1),
    (1, '2018-10-21 10:00:51', 1),
    (1, '2018-10-22 13:19:23', 1),
    (1, '2018-10-22 15:56:11', 0),
    (1, '2018-10-22 16:51:27', 0)
;

SELECT DISTINCT UserID,
       (SELECT MAX(CheckDate) FROM T WHERE CheckType = 1 ANDUserID = TT.UserID) [In],
       (SELECT MIN(CheckDate) FROM T WHERE CheckType = 0 AND UserID = TT.UserID) [Out]
FROM T TT
WHERE UserID = 1;

您的样本中的数据有误(我想),原因是在您的查询中检查了查询中的'1''0',这意味着没有'I',因此您可以使用BIT数据类型代替VARCHAR

如果您的支票类型中确实有'I',则为

SELECT DISTINCT UserID,
       (SELECT MAX(CheckDate) FROM T WHERE CheckType = '1' AND UserID = TT.UserID) [In],
       (SELECT MIN(CheckDate) FROM T WHERE CheckType = '0' AND UserID = TT.UserID) [Out]
FROM T TT
WHERE UserID = 1;

结果

+--------+---------------------+---------------------+
| UserID |         In          |         Out         |
+--------+---------------------+---------------------+
|      1 | 22/10/2018 13:19:23 | 22/10/2018 15:56:11 |
+--------+---------------------+---------------------+