简体   繁体   English

对一个表的复杂SQL查询

[英]Complex SQL query to one table

There is a table: 这里有张桌子:

event |id |timestamp
---------------------
event1|001|21-03-15
event2|001|22-03-15
event1|002|23-03-15
event2|002|24-03-15

What should be a request to display the result: 什么应该是显示结果的请求:

id |event1  |event2  |
----------------------
001|21-03-15|22-03-15|
002|23-03-15|24-03-15|

I think you first need to make a selection of unique id : 你首先需要选择一个唯一的id

SELECT id FROM test GROUP BY id;

And then something like this: 然后这样的事情:

SELECT timestamp
FROM   ... 
WHERE id IN (SELECT id FROM test GROUP BY id) AND event='event1';

Events are known in advance ('event1', 'event2') . 事件是事先知道的('event1', 'event2') If there are recurring events under one id, with different or the same timestamp, add columns to the result, for example: 如果在一个id下有重复事件,具有不同或相同的时间戳,请在结果中添加列,例如:

id |event1  |event2  |event1  |event2  |
----------------------------------------
001|21-03-15|22-03-15|23-03-15|23-03-15|
002|23-03-15|24-03-15|NULL    |NULL    |

You are looking for a simple "pivot" or "crosstab" trick: 您正在寻找一个简单的“枢轴”或“交叉”技巧:

SELECT id
     , min(CASE event WHEN 'event1' THEN timestamp END) AS event1
     , min(CASE event WHEN 'event2' THEN timestamp END) AS event2
FROM   test
GROUP  BY id
ORDER  BY id;

SQL Fiddle. SQL小提琴。

I found a solution, query is looking like this: 我找到了一个解决方案,查询看起来像这样:

SELECT A.id,GROUP_CONCAT(B.timestamp) AS event1, GROUP_CONCAT(C.timestamp) AS event2 FROM (select distinct id from test) A
   LEFT JOIN test B ON B.id=A.id and B.event='event1'
   LEFT JOIN test C ON C.id=A.id and C.event='event2' GROUP BY A.id

You can join records that have event1 with records that have event2 : 您可以将具有event1的记录与具有event2记录event2

SELECT t1.id as id, t1.timestamp as event1, t2.timestamp as event2 
FROM test t1 LEFT JOIN test t2
    ON t1.id = t2.id AND t1.event = 'event1' and t2.event = 'event2'

The query assumes that you always have event1 , so LEFT JOIN was used. 该查询假定您始终具有event1 ,因此使用了LEFT JOIN。

If you need to handle cases where only event2 is available, you can emulate FULL OUTER JOIN as described in Full Outer Join in MySQL 如果您需要处理只有event2可用的情况,您可以模拟FULL OUTER JOIN,如MySQL中的完全外部联接中所述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM