Mysql

如何獲得 3 個子計數查詢的總和並使用屬性對它們進行分組

  • March 11, 2022

我有3個查詢如下:

對於日期 2019-12-02,我正在計算 3 種類型的值。2019-12-02 的總值必須是這 3 個查詢的總和。

第一季度

SELECT count(*) 
FROM XAXBXC_charge_info_ABC_tbl 
WHERE date = '2019-12-02' 
AND cg_response_code = 0 

Q2=>

SELECT count(*) 
FROM XAXBXC_charge_info_ABC_tbl 
WHERE date = '2019-12-02' 
 AND topup_id = 10 
 AND topup_cg_response_code LIKE '0' 

Q3=->

SELECT count(*) 
FROM XAXBXC_charge_info_ABC_tbl 
WHERE date = '2019-12-02' 
 AND topup_id = 11 
 AND topup_cg_response_code LIKE '0'

我正在嘗試按如下方式計算和顯示總和,

Date      | Sum 
2019-12-02|  234

例如:-

對於特定日期,sum 應等於 Q1+Q2+Q3 的總和,並且必須按日期列分組。

有人可以幫助我實現這一目標嗎?我已經被困在這裡一段時間了。

要每天獲得一排,

SELECT date,
      SUM( cg_response_code = 0 ) +
        SUM( topup_id IN (10, 11) AND topup_cg_response_code = 0 )  AS "Sum"
   FROM XAXBXC_charge_info_ABC_tbl 
   GROUP BY date

該模式SUM(boolean)是一種計算“布爾”為 TRUE 的行數的方法。

這在一次數據傳遞中完成了所有工作。

SELECT '2019-12-02' AS `Date`,
      SUM(cg_response_code = 0) 
    + SUM(     topup_id IN (10 , 11) 
           AND topup_cg_response_code LIKE '0'
         ) AS `Sum`
FROM XAXBXC_charge_info_ABC_tbl 
WHERE `date` = '2019-12-02'

PS。LIKE '0'條件太詭異了。我建議將其替換為= 0or = '0',具體取決於topup_cg_response_code數據類型。

這將適用於特定的一天,但我想要每天的記錄 – sadeee nadeee 2 分鐘前

SELECT `date`,
      SUM(cg_response_code = 0) 
    + SUM(     topup_id IN (10 , 11) 
           AND topup_cg_response_code LIKE '0'
         ) AS `Sum`
FROM XAXBXC_charge_info_ABC_tbl
/* WHERE `date` BETWEEN @date1 AND @date2 */
GROUP BY `date`

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