0
I have two tables   Transaction Table :-         
1       txn_id                      
2       txn_issued_by  (mid)        
3       dist_id                 
4       amount                  
5       bank_name           
6       account_no          
7       ben_name            
8       ben_contact         
9       date_of_transaction         
10      date_of_txn_modify          
11      txn_status          
12      bank_response_code          
13      status      
14      modify_by           
15      comm_amount_agent           
16      comm_amount_distributor     
17      comm_amount_sadmin          
18      client_name         
19      client_number           
20      client_add          
21      txn_serial_no           
22      comment_by_moderator    

2)Member Table
   - mid name username photo 

我只是想知道如何处理交易以获得想要的结果,比如......

  • 获取金额介于 525 t0 2500 之间的交易数量
  • 获取金额介于 2501 t0 5050 之间的交易数量
  • 获取金额介于 5051 t0 10100 之间的交易数量

  • 在所有用户(用户明智)中,我的代码是:

<?php
$q_c = "SELECT *,
      COUNT(txn_id) AS count_txn
    FROM TRANSACTION
    WHERE amount >= 525
      AND amount <= 2500
      AND txn_issued_by IN (
        SELECT mid
        FROM members
        )
    GROUP BY txn_issued_by";

$r_c = mysql_query($q_c) or die(mysql_error());
$row_c     = mysql_fetch_array($r_c);
$count_txn = $row_c['count_txn'];
?>

目标如下:

在此处输入图像描述

4

1 回答 1

0

据我了解,您需要仅使用一个查询来计算所有用户在给定金额范围内的交易数量和金额总和。
在这种情况下,如下查询可能会有所帮助:

SELECT txn_issued_by,
  SUM( CASE WHEN amount BETWEEN 525 AND 2500 
       THEN 1 ELSE 0 END ) count_525_to_2500,
  SUM( CASE WHEN amount BETWEEN 2501 AND 5050 
       THEN 1 ELSE 0 END ) count_2501_to_5050,
  SUM( IF( amount BETWEEN 5051 AND 10100, 1, 0 )) count_5051_to_10100,
  COUNT(*) count_total,
  SUM( CASE WHEN amount BETWEEN 525 AND 2500 
       THEN amount ELSE 0 END ) amount_525_to_2500,
  SUM( CASE WHEN amount BETWEEN 2501 AND 5050 
       THEN amount  ELSE 0 END ) amount_2501_to_5050,
  SUM( CASE WHEN amount BETWEEN 5051 AND 10100 
       THEN amount  ELSE 0 END ) amount_5051_to_10100,
  SUM( amount ) amount_total
FROM Transaction
GROUP BY txn_issued_by;

查询使用CASE WHEN ... THEN ... END表达式,IF也可以使用函数(注意查询中的 thirs SUM),但我个人更喜欢CASE WHEN,因为IF它是 MySql 特有的,同时CASE WHEN是 ANSII SQL 兼容的,并且可以在大多数数据库上运行。

以下查询计算所有记录的总值:

SELECT 
  SUM( CASE WHEN amount BETWEEN 525 AND 2500 
       THEN 1 ELSE 0 END ) count_525_to_2500,
  SUM( CASE WHEN amount BETWEEN 2501 AND 5050 
       THEN 1 ELSE 0 END ) count_2501_to_5050,
  SUM( IF( amount BETWEEN 5051 AND 10100, 1, 0 )) count_5051_to_10100,
  COUNT(*) count_total,
  SUM( CASE WHEN amount BETWEEN 525 AND 2500 
       THEN amount ELSE 0 END ) amount_525_to_2500,
  SUM( CASE WHEN amount BETWEEN 2501 AND 5050 
       THEN amount  ELSE 0 END ) amount_2501_to_5050,
  SUM( CASE WHEN amount BETWEEN 5051 AND 10100 
       THEN amount  ELSE 0 END ) amount_5051_to_10100,
  SUM( amount ) amount_total
FROM Transaction;

演示 --> http://www.sqlfiddle.com/#!2/c017b/11

于 2013-11-02T21:11:47.983 回答