0

我有一个名为的数据库表user_transaction,其结构如下:

transaction_id    mediumint(6)   UNSIGNED (PK)
transaction_no    varchar(55)
transaction_cc_avenue_no    varchar(55)
transaction_card_category    varchar(100)
transaction_user_id      varchar(32)
transaction_user_name    varchar(255)
transaction_user_email_id    varchar(255)
transaction_deal_code    varchar(10)
transaction_dc_id    smallint(4)
transaction_amount    float(10,2)
transaction_discount    float(10,2)
transaction_total_amount    float(10,2)
transaction_data_assign    enum('0', '1')
transaction_status    enum('success', 'inprocess', 'fail', 'cancelled')     
transaction_date    bigint(12)
transaction_update_date    bigint(12)
transaction_update_user_id    varchar(32)

我使用 UNIX Timestamp 值将日期存储在列中transaction_date。现在我从 ' dd/mm/yyyy' 格式的表单中获取两个日期,将其转换为 UNIX Timestamp 并在以下查询中使用它。现在我想显示日期编号。在我给定的范围内的所有日期中,不同交易状态的交易(即每个日期发生的交易总数,状态为“成功”、“进行中”、“失败”和“已取消”的交易总数)。这些记录应按交易日期分组。我尝试了很多来获得这个结果,但没有取得任何成功。供您参考,我在下面给出我的查询:

SELECT COUNT(*) `total count`, SUM(transaction_status = 'success') `success`, SUM(transaction_status = 'inprocess') `inprocess`, SUM(transaction_status = 'fail') `fail`, SUM(transaction_status = 'cancelled') `cancelled` FROM user_transaction WHERE transaction_date >= '1325376000' AND transaction_date <=  '1338422400' GROUP BY FROM_UNIXTIME(transaction_date)

任何人都可以在这方面帮助我吗?提前致谢。

4

1 回答 1

1

from_unixtime()函数创建带有时间的日期。你只想要日期:

SELECT date(FROM_UNIXTIME(transaction_date)),
       COUNT(*) `total count`, SUM(transaction_status = 'success') `success`, 
       SUM(transaction_status = 'inprocess') `inprocess`,
       SUM(transaction_status = 'fail') `fail`,
       SUM(transaction_status = 'cancelled') `cancelled`
FROM user_transaction
WHERE transaction_date >= 1325376000 AND transaction_date <= 1338422400
GROUP BY date(FROM_UNIXTIME(transaction_date))

我也'从数字常量中删除了。这些是数字,因此使它们看起来像字符串会产生误导(不会影响性能,只会影响查询的可理解性)。

编辑:

如果要按月分组:

SELECT year(date(FROM_UNIXTIME(transaction_date))),
       month(date(FROM_UNIXTIME(transaction_date))),
       COUNT(*) `total count`, SUM(transaction_status = 'success') `success`, 
       SUM(transaction_status = 'inprocess') `inprocess`,
       SUM(transaction_status = 'fail') `fail`,
       SUM(transaction_status = 'cancelled') `cancelled`
FROM user_transaction
WHERE transaction_date >= 1325376000 AND transaction_date <= 1338422400
GROUP BY year(date(FROM_UNIXTIME(transaction_date))),
         month(date(FROM_UNIXTIME(transaction_date)))

您可能需要更改where包含日期范围的子句。

于 2013-07-12T11:25:36.903 回答