SQL-如何按特定日期模式对交易进行分组?

时间:2018-11-02 10:12:08

标签: sql postgresql group-by

我有一个包含交易数据的表,并希望计算每个transaction_date的记录数。日期格式如下:2018-11-12T01:07:36.000+0000

我尝试了此查询,但未返回任何内容。我的查询可能是什么问题?

我希望输出看起来像transaction_datenumber_of_transactions

SELECT 
transaction_date, COUNT(*)
FROM main.transactions 
WHERE transaction_date LIKE 2018-11-30
GROUP BY 
transaction_date
ORDER BY COUNT(*) DESC;

UPD::是否还可以按日期和日期的每个小时(从00到23)进行分组?

4 个答案:

答案 0 :(得分:2)

修剪时间部分以获取日期

SELECT 
transaction_date::date, COUNT(*) xact_count
FROM main.transactions 
WHERE transaction_date::date = '2018-11-30'::date
GROUP BY 
transaction_date::date
ORDER BY 2 DESC;

对日期戳使用相等性,而不是字符串函数“ LIKE”

我在下面看到了关于每小时分组的问题。

SELECT 
date_trunc('hour',transaction_date), COUNT(*) xact_count
FROM main.transactions 
GROUP BY 
date_trunc('hour', transaction_date)
ORDER BY 2 DESC;

答案 1 :(得分:1)

您可以在下面使用date()函数尝试

using (FileStream s = File.Open("big.json")) // or any other stream
using (StreamReader streamReader = new StreamReader(s))
using (JsonTextReader reader = new JsonTextReader(streamReader))
{
    reader.SupportMultipleContent = true;
    int rowCount = 0;
    var serializer = new JsonSerializer();
    while (reader.Read())
    {
        if (reader.TokenType == JsonToken.StartObject)
        {
            DataRow r = serializer.Deserialize<Contact>(reader);
            rowCount++;
        }
    }
}

OR

SELECT 
date(transaction_date) as tdate, COUNT(*)
FROM main.transactions 
WHERE date(transaction_date) ='2018-11-30'
GROUP BY 
date(transaction_date)
ORDER BY COUNT(*) DESC;

答案 2 :(得分:1)

您应该在where子句中包含trunc(transaction_date)。 trunc会删除您日期中的时间部分,因为当前它使用的是date-time n,而您仅将日期与日期匹配,因此很可能没有结果。

答案 3 :(得分:1)

使用quotation作为'2018-11-30'date'2018-11-30'的日期

with transactions(transaction_date) as
(
 SELECT timestamp'2018-11-30T01:07:36.000+0000' union all
 SELECT timestamp'2018-11-30T03:28:36.000+0000' union all
 SELECT timestamp'2018-11-12T03:28:36.000+0000'   
)
SELECT transaction_date::date, 
       COUNT(*) as number_of_transactions
  FROM transactions 
 WHERE date_trunc('day', transaction_date::date) = date'2018-11-30'
 GROUP BY transaction_date::date
 ORDER BY number_of_transactions DESC;

transaction_date    number_of_transactions
------------------- ----------------------
30.11.2018 00:00:00          2 

,并尝试为ORDER BY子句使用别名。

您可能还希望设置WHERE条件

WHERE cast(transaction_date as date) = '2018-11-30'作为另一种替代样式。

Rextester Demo