使用SQL计算一天中多条记录之间的时差

时间:2018-08-01 20:10:56

标签: mysql sql

我想请您帮忙创建一个查询,让我执行以下操作:

我有一家网上商店,并且有一个数据库,该数据库存储每个用户带有时间戳记的产品。我想形象化“产品会话”,这是指获得用户花在观看产品上的时间除以每天(以及当天观看了多少产品)。

一个例子:

我最近浏览过的具有用户ID的表

My recently viewed items

我想创建一个查询,向我提供此输出

|   DAY    |    TIME  | PRODUCTS |
----------------------------------
|2018-07-31| 00:00:04 |    2     |
----------------------------------
|2018-08-01| 02:38:56 |    5     |

到目前为止,我只能做到这一点:

SELECT DATE(`added_timestamp`) AS day, COUNT(*) AS num_products
FROM tb_recently_viewed 
WHERE `user_id`= 'bac240e3eefbb7dff0bc03d00f392f0d'
GROUP BY DATE(`added_timestamp`)
ORDER BY day

输出一天中看到的产品:

enter image description here

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您在这里:

program Solve;

uses
  Vcl.Forms,
  Unit1 in 'Unit1.pas' {Form1},
  Windows,
  Messages,
  Vcl.Themes,
  Vcl.Styles;

type
  TFixedFormStyleHook = class(TFormStyleHook)
  protected
    procedure WndProc(var AMessage: TMessage); override;
  end;

{ TFixedFormStyleHook }

procedure TFixedFormStyleHook.WndProc(var AMessage: TMessage);
var
  NewMessage: TMessage;
  ncParams: NCCALCSIZE_PARAMS;
begin
  if (AMessage.Msg = WM_NCCALCSIZE) and (AMessage.WParam = 0) then
  begin
    // Convert message to format with WPARAM = TRUE due to VCL styles
    // failure to handle it when WPARAM = FALSE.  Note that currently,
    // TFormStyleHook only ever makes use of rgrc[0] and the rest of the
    // structure is ignored. (Which is a good thing, because that's all
    // the information we have...)
    ZeroMemory(@ncParams,SizeOf(NCCALCSIZE_PARAMS));
    ncParams.rgrc[0] := TRect(Pointer(AMessage.LParam)^);

    NewMessage.Msg := WM_NCCALCSIZE;
    NewMessage.WParam := 1;
    NewMessage.LParam := Integer(@ncParams);
    NewMessage.Result := 0;
    inherited WndProc(NewMessage);

    if Handled then
    begin
      TRect(Pointer(AMessage.LParam)^) := ncParams.rgrc[0];
      AMessage.Result := 0;
    end;
  end
  else
    inherited;
end;

{$R *.res}

begin
  // Register our style hook. An audit of Delphi XE8 VCL source code
  // for registration of the existing TFormStyleHook shows that these are
  // the only two classes we need to register for.
  TCustomStyleEngine.RegisterStyleHook(TForm,TFixedFormStyleHook);
  TCustomStyleEngine.RegisterStyleHook(TCustomForm,TFixedFormStyleHook);

  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  TStyleManager.TrySetStyle('Glossy Light');
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

结果:

select
    date(added_timestamp) as day,
    count(*) as num_products,
    timediff(max(time(added_timestamp)), min(time(added_timestamp))) as time_diff
  from tb_recently_viewed
  group by date(added_timestamp)