[英]Most latest result with separate group in sql
I have table data like below image. 我有如下图所示的表格数据。
Per we enter 6 records in 3times. 每3次输入6条记录。 (morning 2, afternoon 2, evening 2)
(早上2点,下午2点,晚上2点)
When I search by DATE, I want to get the result like below image. 当我在DATE进行搜索时,我想要得到如下图所示的结果。
I want to foreach that result like below. 我想提出如下结果。
I tried this sql query but no luck. 我试过这个SQL查询,但没有运气。
select c.currency, c.date, c.textbody
from currencies c
inner join (
select currency, max(date) as MaxDate
from currencies
group by currency
) cc on c.currency = cc.currency and c.date = cc.MaxDate
where date ='2017-11-20'
group by currency
order by currency'
Story of the Requirement Per day user enter 6 records in 3 session of the time, When the morning time user enter 2 records(EURUSD and GBPUSD). 需求的故事每天用户在3个时段中输入6条记录,早上用户输入2条记录(EURUSD和GBPUSD)。 I will display then in a web page as one group.
然后,我将在网页中显示为一组。 Then in the evening user enter another 2 records(EURUSD and GBPUSD), after that I need to show the latest 2 records are in the top group and previous 2 records and below.
然后在晚上用户输入另外2条记录(EURUSD和GBPUSD),之后我需要显示最新2条记录在顶部组中,并且前2条记录在下面。 per day 6 records 3 groups.
每天6记录3组。
I think you search for GROUP BY timestamp like this: 我认为您要像这样搜索GROUP BY时间戳:
SELECT GROUP_CONCAT(currency) AS currencies, GROUP_CONCAT(text_body) AS text_bodyies, GROUP_CONCAT(timestamp) AS inserted_time
FROM currencies
WHERE date = '2017-11-20'
GROUP BY
CASE
WHEN HOUR(timestamp) < 14 THEN 1 -- MORNING
WHEN HOUR(timestamp) < 17 THEN 2 -- AFTERNOON
WHEN HOUR(timestamp) < 21 THEN 3 -- EVENING
END
ORDER BY timestamp DESC
Make simple query: 进行简单查询:
SELECT currency, textBody FROM currencies
WHERE date = '2017-11-20'
ORDER BY timestamp, currency
Then fetch the data to the $rows
array, add a check to display only the paired rows and display them. 然后将数据提取到
$rows
数组,添加一个检查以仅显示成对的行并显示它们。 In PHP this will be as follows: 在PHP中,将如下所示:
$rowsCount = count($rows);
if (in_array($rowsCount, [2, 4, 6])) {
for ($i = 0; $i < $rowsCount; $rowIndex++) {
echo $rows[$i]['currency'] . ' ' . $rows[$i + 1]['currency'] . ' '
. $rows[$i]['textbody'] . ' ' . $rows[$i + 1]['textbody'].PHP_EOL;
$rowIndex += 1;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.