0

我有 2 个具有相同数据结构的表。

前任:

table 1 (id, pay_amount, package, date)
table 2 (id, pay_amount, package, date)

如何从两个表中获取 Kohana 框架数据并按天计算结果?另外,我如何对字符串进行 substr 并对字符串的其余部分求和(这是一个数字?查看示例中的 package_credit_ 行)。

例如,如果我有这些数据:

Table1: 
(1, 200, "package_credit_300", "12.12.12 12:02:34"), 
(2, 50, "package_credit_50", "12.12.12 15:17:02"), 
(2, 50, "package_credit_50", "13.12.12 16:12:12")

Table2: 
(1, 50, "package_credit_50", "13.12.12 12:02:34"), 
(2, 50, "package_credit_50", "13.12.12 15:17:02"), 
(2, 200, "package_credit_300", "14.12.12 16:12:12")

我想得到类似的东西:

Date: 12.12.12 - Credit: 350 - Paid: 250
Date: 13.12.12 - Credit: 150 - Paid: 150
Date: 14.12.12 - Credit: 300 - Paid: 200
4

2 回答 2

1

尝试这个

   SELECT Substring(t.`date`,1,8)                        AS dates, 
   Sum(Cast(Substring(t.`package`, 16) AS UNSIGNED)) AS `Credit`, 
   Sum(t.pay_amount)                                 AS `Paid` 
    FROM   (SELECT * 
    FROM   table1 
    UNION 
    SELECT * 
    FROM   table2) AS `t` 
    GROUP  BY dates 
    ORDER  BY dates ASC 

在这里看演示

于 2012-12-30T14:44:20.050 回答
1

这不能在 Kohana 中使用 ORM 或 ActiveRecord 来完成。您需要执行此自定义 sql。

SELECT Date(t.`date`)                                    AS `Date`, 
       Sum(Cast(Substring(t.`package`, 16) AS UNSIGNED)) AS `Credit`, 
       Sum(t.pay_amount)                                 AS `Paid` 
FROM   (SELECT * 
        FROM   table1 
        UNION 
        SELECT * 
        FROM   table2) AS `t` 
GROUP  BY `Date` 
ORDER  BY `Date` ASC 
于 2012-12-30T14:11:44.057 回答