Mysql

SUM 函式加 JOINS 的 SQL 查詢

  • December 7, 2018

抱歉,如果之前已經介紹過,但我找不到我的問題的範例

情況:假設我有一張銷售表並想顯示它們

第1步)

SELECT payment_id, amount, payment_date
FROM payment
WHERE payment_date >= '2018-01-01' 
AND payment_date <= NOW());

現在我想總結銷售額或’金額步驟2)

SELECT SUM(amount) as 'Total Amount'
FROM
(SELECT payment_id, amount, payment_date
FROM payment
WHERE payment_date >= '2018-01-01' 
AND payment_date <= NOW()
);

是否可以將“總金額”作為我的第一個表中的新行?即加入付款明細列表,並在列表末尾顯示總金額?

據我了解payment_id是獨一無二的(也許是主要的)。如果是這樣的話:

SELECT payment_id, SUM(amount), payment_date
FROM payment
WHERE payment_date >= '2018-01-01' 
AND payment_date <= NOW())
GROUP BY payment_id WITH ROLLUP;

如果它不是唯一的,或者啟用了 ONLY_FULL_GROUP_BY:

SELECT payment_id, SUM(amount), payment_date
FROM payment
WHERE payment_date >= '2018-01-01' 
AND payment_date <= NOW())
GROUP BY payment_id, payment_date WITH ROLLUP
HAVING payment_date IS NOT NULL or payment_id IS NULL;

payment_date如果可以為 NULL,最後一個查詢將給出錯誤的結果。

引用自:https://dba.stackexchange.com/questions/224388