查询没有给我预期的结果

时间:2011-04-23 11:14:52

标签: mysql sql

ap table

id  tid     code    pid      cl           date  
1   1       1002    17      DC      2011-04-05 16:14:37     
2   1       1002    18      DC      2011-04-05 16:14:37     
3   1       1002    19      DC      2011-04-05 16:14:37     
4   2       1002    12      SC      2011-04-05 16:15:59     
5   2       1002    9       SC      2011-04-05 16:15:59     
6   2       1002    21      SC      2011-04-05 16:15:59     
7   3       1003    20      DC      2011-04-07 14:57:40     
8   3       1003    12      DC      2011-04-07 14:57:40     
9   3       1003    9       DC      2011-04-07 14:57:40     
10  3       1003    21      DC      2011-04-07 14:57:40     
11  4       1002    18      SC      2011-04-08 18:10:04     
12  4       1002    19      SC      2011-04-08 18:10:04     
13  4       1002    22      SC      2011-04-08 18:10:04     
14  5       1001    17      SC      2011-04-08 18:21:10     

在表

   tid  totalamount     code    pstatus     cdate   
    1   65.98           1002        R       2011-04-05 16:14:37 
    2   17.74           1002        R       2011-04-05 16:15:59     
    3   96.36           1003        R       2011-04-07 14:57:40     
    4   25.94           1002        S       2011-04-08 18:10:04     
    5   9               1001        R       2011-05-08 18:21:10     

我试过这样但不正确的

SELECT at.totalamount, at.pstatus, ap.cl
FROM `at` AS at
INNER JOIN ap AS ap ON at.`code` = ap.`code`
WHERE ap.cl = 'SC'
AND at.`code` = '1002'
GROUP BY at.`code`
LIMIT 0 , 30 

我期待结果

   pstatus->S    pstatus->R


code    Stotalamount   Rtotalamount   Sstatus    Rstatus  cl
1002    25.94          17.74          S          R        SC

请任何机构告诉我正确的查询

1 个答案:

答案 0 :(得分:0)

您似乎要添加totalamount两次,一次为R状态,另一次为S状态。

但我不明白你是如何加入ap表的,以及为什么没有添加65.98。是否应该在日期列上完成连接?

这可能有效,但您必须使用不同的数据进行测试才能确定。或者更详细地解释两个表中的列代表什么以及您希望查询显示的内容。

SELECT at.code
     , SUM(IF(at.pstatus='S', at.totalamount, 0))
       AS Stotalamount
     , SUM(IF(at.pstatus='R', at.totalamount, 0))
       AS Rtotalamount
FROM at
WHERE EXISTS 
  ( SELECT 1
    FROM ap
    WHERE at.code = ap.code
      AND at.cdate = ap.date
      AND ap.cl = 'SC'
  )
  AND at.code = 1002
GROUP BY at.code
LIMIT 0 , 30