English 中文(简体)
圆桌会议
原标题:Pivot MySQL table and take missed values from other table
  • 时间:2023-12-11 07:51:40
  •  标签:
  • sql
  • mysql

有两个MySQL表:

table1

id |  time |  status
-----------------------
1  | 10:00 | conn     | 
1  | 10:01 | disconn  | 
2  | 10:02 | conn     | 
2  | 10:03 | disconn  | 
3  | 10:04 | conn     | 


table2

id |  time |
------------
3  | 10:05 |

If there is no disconn time value for ceratin id then take it from table2. What is sql query to get wished result:

id | conn | disconn|
--------------------
1  | 10:00| 10:01  |
2  | 10:02| 10:03  |
3  | 10:04| 10:05  |
最佳回答

您可使用<条码>LEFT JOIN和COALESCE。 样本代码:

SELECT 
    t1.id,
    t1.time AS conn,
    COALESCE(t1_disconn.time, t2.time) AS disconn
FROM table1 t1
LEFT JOIN table1 t1_disconn ON t1.id = t1_disconn.id AND t1_disconn.status =  disconn 
LEFT JOIN table2 t2 ON t1.id = t2.id
WHERE t1.status =  conn 
ORDER BY t1.id;

样本产出如下:

“enterography

http://dbfiddle.uk/4vp-wO47“rel=“nofollow noreferer”>fiddlelink

问题回答

或者, 也可使用<代码>。 由<<0>无<>代码>的组别加入如下:

SELECT
    T1.ID,
    MAX(CASE WHEN T1.STATUS =  conn  THEN T1.TIME END) AS CONN,
    COALESCE(MAX(CASE WHEN T1.STATUS =  disconn  THEN T1.TIME END), T2.TIME) AS DISCONN
  FROM
    table1 T1
      LEFT JOIN table2 T2 ON T1.ID = T2.ID
 GROUP BY T1.ID, T2.TIME
 ORDER BY T1.ID;




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签