我想做这样的BOLD部分。我不知道是否有可能。请帮帮我。 之间的部分 //开始和//结束 有可能吗?
SELECT a.id, b.id, b.number, c.total,
//Start
SUM(total WHERE c.id=a.id) AS sum_total
//End
FROM table_1 a
LEFT JOIN table_2 b ON a.id=b.id
INNER JOIN table_4 ON b.company=c.company
INNER JOIN table_3 c ON b.number=c.id_number
WHERE b.date BETWEEN 'date_1' AND 'date_2'
ORDER BY d.company ASC
答案 0 :(得分:1)
当然有可能。请尝试以下SQL:
SELECT a.id, b.id, b.number, SUM(c.total)TOTAL,
//Start
SUM(case when c.id=a.id then total else 0 end) AS sum_total
//End
FROM table_1 a
LEFT JOIN table_2 b ON a.id=b.id
INNER JOIN table_4 ON b.company=c.company
INNER JOIN table_3 c ON b.number=c.id_number
WHERE b.date BETWEEN 'date_1' AND 'date_2'
GROUP BY 1,2,3
ORDER BY d.company ASC
答案 1 :(得分:0)
您使用GROUP BY
来执行此操作,类似于:
SELECT a.id, b.id, b.number, c.total,
//Start
SUM(total) AS sum_total
//End
FROM table_1 a
LEFT JOIN table_2 b ON a.id=b.id
INNER JOIN table_4 ON b.company=c.company
INNER JOIN table_3 c ON b.number=c.id_number
WHERE b.date BETWEEN 'date_1' AND 'date_2' AND
c.id = a.id
GROUP BY a.id, b.id
ORDER BY d.company ASC
http://www.w3resource.com/sql/aggregate-functions/sum-with-group-by.php