0

我有一个带有以下数据的表loan_repayed

l_id   i_no  dif     interval   amt
===================================  
32     33   735      3        27774
32     34   707      3        27774
32     35   676      3        27774

我有以下数据的其他表格间隔

id  min max
============
1   30   60
2   60   90
3   90   9999

当我执行以下查询时

 select 
    lpt.l_Id, 
    d.id, 
    ifnull(sum(lpt.amt),0) 
 from 
     loan_repayed lpt 
 left join 
     interval d on lpt.interval = d.id 
 where 
     lpt.loan_id = 32
 group by 
     lpt.l_id, d.id;

我期待得到

   l_id      interval   amt
   =========================
    32       1           0
    32       2           0
    32       3           83322

但我只排了 1 行

 l_id      interval     amt
 ===========================
   32        3         333298

有人可以建议我在哪里出错....谢谢你

4

2 回答 2

2

尝试这个:

SELECT
  IFNULL(lpt.l_id, 32) AS L_ID, 
  d.id, 
  IFNULL(SUM(lpt.amt),0) 
FROM `interval` AS d 
LEFT JOIN loan_repayed AS lpt ON lpt.interval = d.id 
GROUP BY lpt.l_id, d.id;

SQL 小提琴演示


更新 1

对于多个值,您可以这样做:

SELECT DISTINCT
  d.l_id,
  d.id,
  IFNULL(l.totalamt, 0) AS totalamt
FROM
(
  SELECT l.l_id, d.id
  from 
  (             -- <---------- here you list the values you want
    SELECT 32 AS L_ID
    UNION ALL 
    SELECT 32
    UNION ALL
    SELECT 33
    UNION ALL
    SELECT 34
  ) AS l CROSS JOIN(SELECT id from `interval`) as d
) AS d
LEFT JOIN
(
select 
    lpt.L_ID, 
    d.id, 
    ifnull(sum(lpt.amt),0) AS totalamt
 from `interval` AS d
 INNER JOIN loan_repayed lpt on lpt.interval = d.id 
group by lpt.l_id, d.id
) AS l ON l.l_id = d.l_id AND d.id = l.id ;

更新的 SQL Fiddle 演示

这会给你:

| L_ID | ID | TOTALAMT |
------------------------
|   32 |  1 |        0 |
|   32 |  2 |        0 |
|   32 |  3 |    83322 |
|   33 |  1 |        0 |
|   33 |  2 |        0 |
|   33 |  3 |        0 |
|   34 |  1 |        0 |
|   34 |  2 |        0 |
|   34 |  3 |        0 |
于 2013-02-14T09:03:04.950 回答
0
 select lpt.l_Id, d.id, ifnull(sum(lpt.amt),0) from 
 loan_repayed lpt left join interval d on lpt.interval = d.id 
 where lpt.loan_id = 32
 group by d.id,lpt.l_id;

或.. 使用having而不是where

select lpt.l_Id, d.id, ifnull(sum(lpt.amt),0) from
loan_repayed lpt left join interval d on lpt.interval = d.id
group by d.id,lpt.l_id having lpt.loan_id = 32;
于 2013-02-14T08:56:59.787 回答