SQL - 子串查询结果

时间:2016-09-07 14:06:43

标签: sql sql-server datetime

我有以下列的表

  log_id      INT PRIMARY KEY 
  emp_name    VARCHAR(7) NOT NULL
  date_log    VARCHAR(23) NOT NULL
  in_am       VARCHAR(8) NULL
  out_am      VARCHAR(4) NULL
  total_am    VARCHAR(4) NULL
  in_pm       VARCHAR(4) NULL
  out_pm      VARCHAR(8) NULL
  total_pm    VARCHAR(4) NULL
  grand_total VARCHAR(4) NULL
  id          INT  Foreign key here

假设我已经获得了in_am和out_am的值,我希望得到它之间的区别我做了这个。

 select cast(out_am as datetime) - cast(in_am as datetime) from Table

结果如下:

1900-01-01 00:00:07.000

但我想要这个结果

00:00:07

我尝试将其子串起来:

select substring((cast(out_am as datetime) - cast(in_am as datetime)),15,20) from table

但它不起作用。

5 个答案:

答案 0 :(得分:1)

只需使用DATETIME格式108输出HH:MM:SS,如下所示:

SELECT CONVERT(VARCHAR(8), (CAST(out_am AS DATETIME) - CAST(in_am AS DATETIME)), 108) FROM Table

答案 1 :(得分:0)

你可以尝试使用convert(time,getdate())

答案 2 :(得分:0)

如果您知道值总是少于一天,则可以将差值转换为time

select cast(cast(out_am as datetime) - cast(in_am as datetime) as time)
from Table;

或者,您可以转换为字符串并提取时间组件:

select right(convert(varchar(255), cast(out_am as datetime) - cast(in_am as datetime) ), 8)

答案 3 :(得分:0)

您可以使用CASTFORMAT

SELECT FORMAT(CAST(CAST(out_am AS DATETIME) - CAST(in_am AS DATETIME) AS TIME), N'hh\:mm\:ss')
FROM TABLE

答案 4 :(得分:0)

您可以将这些varchars转换或转换为时间类型 并将差异以秒为单位添加到0时间。

SELECT
CREDITOS.Id                AS  [Num Credito],          CREDITOS.CLIENTE            AS  [Cedula Cliente],
CLIENTES.NOMBRES           AS  [Nombres Cliente],      CLIENTES.APELLIDOS          AS  [Apellidos Cliente],
CREDITOS.FECHA_INICIAL     AS  [Fecha Inicial],        CREDITOS.FECHA_FINAL        AS  [Fecha Final],
CREDITOS.CONCEPTO          AS  [Concepto],             CREDITOS.VALOR_CREDITO      AS  [Valor],
CREDITOS.NUMERO_CUOTAS     AS  [Numero Cuotas],        CREDITOS.MONTO              AS  [Monto],
CREDITOS.PORCENTAJE        AS  [Porcentaje],           CREDITOS.UTILIDAD           AS  [Utilidad],
CREDITOS.VALOR_CUOTAS      AS  [Valor Cuotas],         CREDITOS.EMPLEADO           AS  [Cedula Empleado],
EMPLEADOS.NOMBRES          AS  [Nombres Empleado],     EMPLEADOS.APELLIDOS         AS  [Apellidos Empleado],
t.Conteo                   AS  [Días de retraso],      t.[Total Recaudo]

FROM (CLIENTES 
INNER JOIN (EMPLEADOS 
INNER JOIN (CREDITOS 
LEFT JOIN (
   SELECT CREDITOS.Id AS Cred,
          Nz(Count(IIf(CREDITOS.VALOR_CUOTAS = RECAUDOS.SALDO,1,Null)),0) AS Conteo,
          Nz(Sum(RECAUDOS.VALOR_RECAUDO),0) AS [Total Recaudo]
   FROM CREDITOS 
   INNER JOIN RECAUDOS
   ON(CREDITOS.Id = RECAUDOS.CREDITO)
   GROUP BY CREDITOS.Id
)  AS t 
ON CREDITOS.Id = t.Cred) 
ON EMPLEADOS.ID = CREDITOS.EMPLEADO) 
ON CLIENTES.Id = CREDITOS.CLIENTE)

LEFT用于仅从当时获得HH:MM:SS格式化的varchar。