具有重复响应的Union语句,即使是group by

时间:2014-06-19 16:05:17

标签: sql

UNION with statement with back loan_type_response

    lt.loan_type_id,
    lt.loan_type_name,
         (SELECT CONCAT(ROUND(SUM(la.loan_amount), 0), ', ', COUNT(loan.loan_id))
                FROM loan
                JOIN loan_amount la ON la.loan_amount_id = loan.ref_loan_amount_id
                JOIN loan2event l2e ON l2e.ref_loan_id = loan.loan_id AND l2e.end IS NULL and DATE(l2e.start) = CURDATE() AND l2e.ref_event_id IN (1301)
                WHERE loan.ref_loan_type_id = lt.loan_type_id) as amount_count
FROM loan_type lt
WHERE lt.active = 1
  GROUP BY lt.loan_type_id

UNION

 SELECT
        lt.loan_type_id,
        lt.loan_type_name,           
             (SELECT CONCAT(ROUND(SUM(la.loan_amount), 0), ', ', COUNT(loan.loan_id))
                    FROM loan
                    JOIN loan_amount la ON la.loan_amount_id = loan.ref_loan_amount_id
                    JOIN loan2event l2e1 ON l2e1.ref_loan_id = loan.loan_id AND l2e1.end IS NULL AND l2e1.ref_event_id IN ("1004 "," 1101 "," 1105")
                   WHERE loan.ref_loan_type_id = lt.loan_type_id ) as amount_count
FROM loan_type lt
   WHERE lt.active = 1
  GROUP BY lt.`loan_type_name`

响应:

New 1200, 4
Advanced    750, 5
Basic   NULL
New 6050, 17
Advanced    NULL
Basic   3150, 11

希望看到它按loan_id分组

   New Loan 7250, 21
   Advanced 750, 5
   Basic    3150, 11

1 个答案:

答案 0 :(得分:0)

下面是我将如何在SQL服务器中执行此操作的基本语法,我想它应该可以在MySQL中运行并进行一些调整 -

SELECT loan_type_id, loan_type_name, SUM(amount_count) FROM (SELECT lt.loan_type_id, lt.loan_type_name, (SELECT CONCAT(ROUND(SUM(la.loan_amount), 0), ', ', COUNT(loan.loan_id)) FROM loan JOIN loan_amount la ON la.loan_amount_id = loan.ref_loan_amount_id JOIN loan2event l2e ON l2e.ref_loan_id = loan.loan_id AND l2e.end IS NULL and DATE(l2e.start) = CURDATE() AND l2e.ref_event_id IN (1301) WHERE loan.ref_loan_type_id = lt.loan_type_id) as amount_count FROM loan_type lt WHERE lt.active = 1 GROUP BY lt.loan_type_id UNION SELECT lt.loan_type_id, lt.loan_type_name, (SELECT CONCAT(ROUND(SUM(la.loan_amount), 0), ', ', COUNT(loan.loan_id)) FROM loan JOIN loan_amount la ON la.loan_amount_id = loan.ref_loan_amount_id JOIN loan2event l2e1 ON l2e1.ref_loan_id = loan.loan_id AND l2e1.end IS NULL AND l2e1.ref_event_id IN ("1004 "," 1101 "," 1105") WHERE loan.ref_loan_type_id = lt.loan_type_id ) as amount_count FROM loan_type lt WHERE lt.active = 1 GROUP BY lt.loan_type_name) UnionResult GROUP BY loan_type_id, loan_type_name