sql查询创建计算字段

Posted

技术标签:

【中文标题】sql查询创建计算字段【英文标题】:Sql query to create a calculated field 【发布时间】:2014-11-12 22:35:03 【问题描述】:

我有一个这样的数据库表: 希望我能解释清楚,让你明白。

我想计算每个员工工作了多少小时。 例如,对于“Arjeta Domi”,我们有 Cell(2,3) - Cell(3,3) + Cell(4,3) + Cell(5,3),每个 logOut 时间与 Login 时间的差异。

我想要的决赛桌将有这些列:CardNoUserNameDatePauseTimeWorkTime

我试过这个查询:取自duplicate

SELECT DISTINCT
  [Card NO], 
  [User Name],  
  (
    SELECT
      MIN(DateTime) AS [Enter Time], 
      MAX(DateTime) AS [Exit Time], 
      MAX(DateTime) - MIN(DateTime) AS [Inside Hours] 
    FROM
      ExcelData
  ) 
FROM
  ExcelData
GROUP BY
  [Card NO], [User Name], DateTime

DateTime 列的类型是 String,而不是 DateTime。 我正在使用 MS Access 数据库。

【问题讨论】:

【参考方案1】:

选择所有带有“m001-1-In”且 DateTime 为 I 的行,并将合适的“m001-1-Exit”行添加到其中,子查询为 O,如下所示:

SELECT t1.[Card No], t1.[User Name],dateTime as I
,(Select TOP 1 dateTime from Tab t2 where  t2.[Card No]= t1.[Card No] 
and  t2.[User Name]= t1.[User Name] and  t2.Addr='m001-1-Exit' 
and t2.DateTime>t1.datetime ORDER by DateTime) as O
FROM Tab t1
where t1.Addr='m001-1-In' 

现在很容易封装它,如下面的 Prepared 所示,并将我们的 SUM 和 Grouping 添加到此:

SELECT [Prepared].[Card No], [Prepared].[User Name], SUM(DateDiff('n',I,O))/60 AS Hours
FROM (
      SELECT t1.[Card No], t1.[User Name],dateTime as I
    ,(Select TOP 1 dateTime from Tab t2 where  t2.[Card No]= t1.[Card No] 
      and  t2.[User Name]= t1.[User Name] and  t2.Addr='m001-1-Exit' 
      and t2.DateTime>t1.datetime ORDER by DateTime) as O
FROM Tab t1
where t1.Addr='m001-1-In' 
)  AS [Prepared]
GROUP BY [Prepared].[Card No], [Prepared].[User Name]

如果您需要限制 DateRange,请将所需条件添加到行 where t1.Addr='m001-1-In'

【讨论】:

您好,我想问您是否可以使用此查询进行插入。例如:INSERT INTO fTable(f1,f2,f3) SELECT g1,h2,g3 FROM "yourQuery" Inner Join hTable in [here the fields]?很有帮助,谢谢! 我不确定我是否理解,但是像Insert into dest (f1,f2,f3) Select a.[Card No],x.SomeField, a.Hours from ( <myquery> ) a Inner JOIN Tabx x ON x.f1=a.[Card No] AND ....... 这样的东西会起作用 是的,完全一样。好的,我会测试它。谢谢! 好的,看起来不错。我有最后一个请求。我要插入的值之一是变量。前任。 INSERT INTO DEST(f1,f2,f3) SELECT variable, x.SomeField, a.Hours FROM () A Inner Join Tabx x On x.id = a.[cardNo]。我猜这个变量不能像这样从“From ()...”插入!【参考方案2】:

试试这个:

SELECT CardNo, UserName, SUM(DATEDIFF('h',DateTime,(SELECT MIN(Datetime) 
                                                    FROM table as t2 
                                                    WHERE t1.CardNo=t2.CardNo
                                                        AND t2.Addr like '%Exit' 
                                                        AND t2.DateTime > t1.DateTime )))
FROM table as t1
WHERE Addr like '%In'
GROUP BY CardNo, UserName

【讨论】:

以上是关于sql查询创建计算字段的主要内容,如果未能解决你的问题,请参考以下文章

要计算的特定 SQL 查询 [重复]

从另一个查询访问SQL查询

MS SQL更新时变量函数子查询及字段计算顺序探索

MS SQL更新时变量函数子查询及字段计算顺序探索

SQL 查询重新计算运行总计

sql 查询排除一个字段的其他字段