【问题标题】:create one concatenated value out of multiple rows从多行中创建一个连接值
【发布时间】:2021-12-08 03:28:46
【问题描述】:

请参阅下面的可重现示例。

需要做什么

查看代码中的 cmets:使用 '2021-01-01'(column: Date) 和 'A'(column: Tote) 创建唯一的手提包,同时从 'hat'(column: content) 和 'cat 创建连接字符串'(列:内容)按字母顺序排列。

可重现的例子:

CREATE OR REPLACE TABLE
`first_table` (
  `Date` string NOT NULL,
  `TotearrivalTimestamp` string  NOT NULL,
  `Tote` string NOT NULL,
  `content` string NOT NULL,
  `location` string NOT NULL,
);
INSERT INTO `first_table` (`Date`, `TotearrivalTimestamp`, `Tote`, `content`, `location`) VALUES
  ('2021-01-01', '13:00','A','hat','1'), #first tote
  ('2021-01-01', '13:00','A','cat','1'), #first tote
  ('2021-01-01', '14:00', 'B', 'toy', '1'),
  ('2021-01-01', '14:00', 'B', 'cat', '1'),
  ('2021-01-01', '15:00', 'A', 'toy', '1'),
  ('2021-01-01', '13:00', 'A', 'toy', '1'),
  ('2021-01-02', '13:00', 'A', 'hat', '1'),
  ('2021-01-02', '13:00', 'A', 'cat', '1');
  

CREATE OR REPLACE TABLE
`desired_result` (
  `Date` string NOT NULL,
  `Tote` string NOT NULL,
  `TotearrivalTimestamp` string  NOT NULL,
  `content_combination` string NOT NULL,
 );
INSERT INTO `desired_result` (`Date`, `Tote`, `TotearrivalTimestamp`, `content_combination`) VALUES

('2021-01-01', 'A', '13:00', 'cathat'), #first tote
('2021-01-01', 'B', '14:00', 'cattoy'),
('2021-01-01', 'A', '15:00', 'toy'),
('2021-01-02', 'A', '13:00', 'cathattoy');

【问题讨论】:

  • 您使用的是什么 DBMS?

标签: sql group-by


【解决方案1】:

STRING_AGG() 成功了——对我有用

【讨论】:

    【解决方案2】:

    从反引号我断定这是 MySQL。在 MySQL 中,字符串聚合函数称为 GROUP_CONCAT:

    select
      date, tote,totearrivaltimestamp,
      group_concat(content order by content separator '') as content_combination
    from mytable
    group by date, tote,totearrivaltimestamp
    order by date, tote,totearrivaltimestamp;
    

    【讨论】:

      猜你喜欢
      • 2014-05-29
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 2021-12-13
      • 2014-10-28
      相关资源
      最近更新 更多