2017-03-09 62 views
0

我試圖用下面的圖片顯示原生SQL查詢的結果,目前我不確定是否有任何方法可以使用只有SQL來獲得此結果。特定結果的SQL使用次數或總數

我就是在這個查詢,但不知道目前進一步:

SELECT 
    receipts.client_code clientCode, 
    date_trunc('MON', receipts.create_date) monthYear, 
    COUNT(date_trunc('MON', receipts.create_date)) receipts, 
    subReceipts.total total 
    FROM receipts 
    LEFT JOIN (SELECT 
     receipts.client_code clientCode, 
     date_trunc('MON', receipts.create_date) monthYear, 
     COUNT(date_trunc('MON', receipts.create_date)) total 
     FROM receipts 

     GROUP BY 
     receipts.client_code, 
     date_trunc('MON' ,receipts.create_date) 
     ORDER BY 
     date_trunc('MON' ,receipts.create_date) 
    ) subReceipts ON subReceipts.clientCode = receipts.client_code 
    GROUP BY 
    receipts.client_code, 
    date_trunc('MON' ,receipts.create_date), 
    subReceipts.total 
    ORDER BY 
    date_trunc('MON' ,receipts.create_date) 

示例SQL數據和數據庫表創建腳本:

CREATE TABLE receipts 
(
receipt_id int primary key, 
client_code varchar not null, 
create_date date not null 
); 

insert into receipts (receipt_id, client_code, create_date) values (1, 'fx90', to_date('2016/01/11', 'yyyy/MM/dd')); 
insert into receipts (receipt_id, client_code, create_date) values (2, 'fx90', to_date('2016/02/12', 'yyyy/MM/dd')); 
insert into receipts (receipt_id, client_code, create_date) values (3, 'fx90', to_date('2016/02/20', 'yyyy/MM/dd')); 
insert into receipts (receipt_id, client_code, create_date) values (4, 'fx90', to_date('2016/03/11', 'yyyy/MM/dd')); 
insert into receipts (receipt_id, client_code, create_date) values (5, 'fx90', to_date('2016/03/12', 'yyyy/MM/dd')); 
insert into receipts (receipt_id, client_code, create_date) values (6, 'fx90', to_date('2016/03/19', 'yyyy/MM/dd')); 

結果示例

sample result with params

+0

貌似要在 「運行總計」 添加到每一行。 'DATE_TRUNC'不是一個有效的MySQL函數,所以不清楚爲什麼這個問題是用mysql標記的。 – spencer7593

+0

真 - 刪除mysql標記 – PDS

回答

1

對於PostgreSQL:

SELECT clientCode, monthYear, receipts, 
     sum(receipts) over(order by monthYear) as total 
    FROM (
    SELECT receipts.client_code clientCode, 
      date_trunc('MON', receipts.create_date) monthYear, 
      COUNT(1) receipts 
     FROM receipts 
     GROUP BY receipts.client_code, monthYear 
) X 
ORDER BY monthYear 
+0

這是我所尋找的 - 你能告訴我什麼是使用'count(1)' 它似乎只是爲了使用組? – PDS

+0

@Dave'count()'計數任何NOT NULL值。 '1'不爲空:)'count(1)'等於'count(date_trunc('MON',receipts.create_date))',但可能更快 – Mike

2

假設mysql,你可以這樣做:

set @running_total := 0; 
SELECT 
    client_code, 
    CONCAT(MONTH(create_date), ' - ', YEAR(create_date)) as month_year, 
    COUNT(receipt_id) AS receipts_month, 
    (@running_total := @running_total + COUNT(receipt_id)) as total_receipts 
FROM receipts 
GROUP BY client_code, MONTH(create_date), YEAR(create_date) 
ORDER BY receipt_id;