将多行组合成一行

时间:2017-12-27 03:31:53

标签: mysql sql

我在尝试查询mysql时遇到了一些问题。 我有一些如下数据:

enter image description here

但与此同时,我想在一个日期加入所有数据,就像这样:

enter image description here

CAN SOMEBODY帮助我???

以下是我的查询:

SELECT DATE_FORMAT(PRAY_TIME, '%d-%m-%Y') 'SCH_DATE',
IF(PRAY_SCH = 'Subuh', LEFT(RIGHT(DATE_SUB(PRAY_TIME, INTERVAL 17 HOUR), 8), 5), '-') 'SUBUH',
IF(PRAY_SCH = 'Dzuhur', LEFT(RIGHT(DATE_SUB(PRAY_TIME, INTERVAL 5 HOUR), 8), 5), '-') 'DZUHUR',
IF(PRAY_SCH = 'Ashar', LEFT(RIGHT(DATE_ADD(PRAY_TIME, INTERVAL 7 HOUR), 8), 5), '-') 'ASHAR',
IF(PRAY_SCH = 'Maghrib', LEFT(RIGHT(DATE_ADD(PRAY_TIME, INTERVAL 7 HOUR), 8), 5), '-') 'MAGHRIB',
IF(PRAY_SCH = 'Isya', LEFT(RIGHT(DATE_ADD(PRAY_TIME, INTERVAL 7 HOUR), 8), 5), '-') 'ISYA'
FROM T_TABLE_ADZAN_2018 WHERE ID_CITY = '1'
ORDER BY DATE(PRAY_TIME) ASC;

2 个答案:

答案 0 :(得分:2)

您可以使用聚合:

SELECT DATE_FORMAT(PRAY_TIME, '%d-%m-%Y') as SCH_DATE,
       MAX(CASE WHEN PRAY_SCH = 'Subuh', LEFT(RIGHT(DATE_SUB(PRAY_TIME, INTERVAL 17 HOUR), 8), 5) END) as SUBUH,
       MAX(CASE WHEN PRAY_SCH = 'Dzuhur', LEFT(RIGHT(DATE_SUB(PRAY_TIME, INTERVAL 5 HOUR), 8), 5) END) as DZUHUR,
       MAX(CASE WHEN PRAY_SCH = 'Ashar', LEFT(RIGHT(DATE_ADD(PRAY_TIME, INTERVAL 7 HOUR), 8), 5) END) as ASHAR,
       MAX(CASE WHEN PRAY_SCH = 'Maghrib', LEFT(RIGHT(DATE_ADD(PRAY_TIME, INTERVAL 7 HOUR), 8), 5) END) as MAGHRIB,
       MAX(CASE WHEN PRAY_SCH = 'Isya', LEFT(RIGHT(DATE_ADD(PRAY_TIME, INTERVAL 7 HOUR), 8), 5) END) as ISYA
FROM T_TABLE_ADZAN_2018
WHERE ID_CITY = 1
GROUP BY DATE_FORMAT(PRAY_TIME, '%d-%m-%Y') ASC;

注意:

  • GROUP BY密钥应该是SELECT
  • 的密钥
  • 不要使用单引号作为列别名。仅对字符串和日期常量使用单引号。
  • 使用MAX()应该做你想做的事。
  • 据推测,ID_CITY是一个数字,因此请将其与数字进行比较,而不是字符串。
  • CASE表达式为ANSI标准; IF()是特定于MySQL的。

答案 1 :(得分:0)

你可以这样试试:

select
    DATE_FORMAT(a.PRAY_TIME, '%d-%m-%Y') 'SCH_DATE',
    LEFT(RIGHT(DATE_SUB(b.PRAY_TIME, INTERVAL 17 HOUR), 8), 5) as SUBUH,
    LEFT(RIGHT(DATE_SUB(c.PRAY_TIME, INTERVAL 5 HOUR), 8), 5) as DZUHUR,
    LEFT(RIGHT(DATE_ADD(PRAY_TIME, INTERVAL 7 HOUR), 8), 5) as MAGHRIB,
    LEFT(RIGHT(DATE_ADD(PRAY_TIME, INTERVAL 7 HOUR), 8), 5) as ISYA
    from T_TABLE_ADZAN_2018 as a 
    left join T_TABLE_ADZAN_2018 as b on DATE_FORMAT(a.PRAY_TIME,'%d-%m-%Y')=DATE_FORMAT(a.PRAY_TIME,'%d-%m-%Y') and b.PRAY_SCH='Dzuhur'
    left join T_TABLE_ADZAN_2018 as c on DATE_FORMAT(a.PRAY_TIME,'%d-%m-%Y')=DATE_FORMAT(c.PRAY_TIME,'%d-%m-%Y') and b.PRAY_SCH='Ashar'
    left join T_TABLE_ADZAN_2018 as d on DATE_FORMAT(a.PRAY_TIME,'%d-%m-%Y')=DATE_FORMAT(d.PRAY_TIME,'%d-%m-%Y') and b.PRAY_SCH='Maghrib'
    left join T_TABLE_ADZAN_2018 as e on DATE_FORMAT(a.PRAY_TIME,'%d-%m-%Y')=DATE_FORMAT(e.PRAY_TIME,'%d-%m-%Y') and b.PRAY_SCH='Maghrib' WHERE a.ID_CITY = '1'