2014-12-13 88 views
0

我有如下3計數和在同一個表中組總和按日期

| DATE | FULL/PART | AMMOUNT | CODETYPE | 
|2014-01-02|  PART  |  3.00  |  02  | 
|2014-01-02|  PART  | 10.00  |  02  | 
|2014-01-03|  PART  |  5.00  |  01  | 
|2014-01-03|  FULL  | 10.00  |  03  | 
|2014-01-01|  FULL  | 10.00  |  01  | 
|2014-01-01|  FULL  | 10.00  |  01  | 

我想生成的統計輸出如下

| DATE | CODETYPE | SUM(AMMOUNT)FULL | COUNT(AMMOUNT)FULL | SUM(AMMOUNT)PART | COUNT(AMMOUNT)PART| 
|2014-01-01|  01  |  20.00  |   2  |   0.00  |   0  | 
|2014-01-03|  03  |  10.00  |   1  |   0.00  |   0  | 
|2014-01-03|  01  |   0.00  |   0  |   5.00  |   1  | 
|2014-01-02|  02  |   0.00  |   0  |  13.00  |   2  | 

查詢我迄今爲止類似一個表: -

SELECT DATE,CODETYPE,sum(AMMOUNT),count(AMMOUNT) 
FROM myTABLE 
WHERE CODETYPE='01' && FULL/PART='FULL' && DATE BETWEEN '2014-01-01' AND '2014-01-31' 


SELECT DATE,CODETYPE,sum(AMMOUNT),count(AMMOUNT) 
FROM myTABLE 
WHERE CODETYPE='02' && FULL/PART='PART' && DATE BETWEEN '2014-01-01' AND '2014-01-31' 


SELECT DATE,CODETYPE,sum(AMMOUNT),count(AMMOUNT) 
FROM myTABLE 
WHERE CODETYPE='03' && FULL/PART='PART' && DATE BETWEEN '2014-01-01' AND '2014-01-31' 

最後GROUP BY DATE,CODETYPE

每個日期都有完整的或部分的,不同的CODETYPE(01,02,03,...),我必須將數據彙總到上面的輸出中,

DATE 2014-01-01,sum()並計數()其中CODETYPE = '01'和按日期分組的AMMOUNT

我該如何實現它?或者是否有任何查詢函數可以解決這個我不知道的問題(我是新的sql)?

編輯: 日期範圍和CODETYPE是基於用戶的願望。

回答

3

你想有條件聚集:

SELECT DATE, CODETYPE, 
     SUM(CASE WHEN `FULL/PART` = 'FULL' THEN AMOUNT END) as AMOUNT_FULL, 
     SUM(`FULL/PART` = 'FULL') as CNT_FULL, 
     SUM(CASE WHEN `FULL/PART` = 'PART' THEN AMOUNT END) as AMOUNT_PART, 
     SUM(`FULL/PART` = 'PART') as CNT_PART 
FROM myTABLE 
WHERE FDATE BETWEEN '2014-01-01' AND '2014-01-31' 
GROUP BY DATE, CODETYPE 
+0

比我建議的更優雅。不知道你能做到這一點。 – benji 2014-12-13 03:58:37

+0

您必須使用CNT_FULL和CNT_PART的計數 – 2014-12-13 04:01:54

+0

@IndraKumarS。 。 。我不知道你的意思。上面的代碼是正確的。如果你使用'count()',你會得到錯誤的答案。 MySQL將數字上下文中的布爾值視爲整數,其中true爲1,false爲0. sum()計算匹配值的數量。 – 2014-12-13 04:03:28