我是SQL新手,不是程序员。苦苦挣扎着以下。最后,我放弃并寻求你的帮助。
SELECT `AccountNo`, -SUM(`Amount`) AS "Charged"
FROM `databasenamex`.`tablenamex`
WHERE (`Charge progress` BETWEEN 1 AND 2)
OR IFNULL(`Charge progress` BETWEEN 1 AND 2, 0)
GROUP BY `AccountNo`;
此查询仅返回对应于满足所述条件的记录总和的两行结果。我认为...或ifnull()...部分将包括列出未满足BETWEEN条件的所有其他AnnountNo。总共有10个AccountNo可选条目,只有两个不是零和。顺便说一句,查询结果是相同的没有...或ifnull()...部分。
该表包含包含Amount,AccountNo和Charge进度的列(等等)。
设置此查询的正确方法是什么?
答案 0 :(得分:0)
这似乎是你想要的:
SELECT `AccountNo`, -SUM(`Amount`) AS "Charged"
FROM `databasenamex`.`tablenamex`
WHERE `Charge progress` BETWEEN 1 AND 2 OR
`Charge progress` IS NULL
GROUP BY `AccountNo`;
但是你的问题是,你想要所有的行。如果您想要所有帐户,为什么要使用where
条款?
答案 1 :(得分:0)
我不确定我是否理解您的问题,但现在尝试一下:
SELECT `AccountNo`, -SUM(`Amount`) AS "Charged"
FROM `databasenamex`.`tablenamex`
WHERE COALESCE(`Charge progress`, 1) BETWEEN 1 AND 2
GROUP BY `AccountNo`;
COALESCE是一个函数,它返回它最左边的非空值。所以如果Charge progress
为空,则1是1到2之间的结果。
编辑:使用表定义,一些示例数据和修改过的查询进行更新:
CREATE TABLE tablesql
( ID int(10) NOT NULL AUTO_INCREMENT
, AccountNo tinyint(3) NOT NULL
, Amount smallint(5) DEFAULT NULL
, Charge progress tinyint(2) DEFAULT NULL
, PRIMARY KEY (ID)
, UNIQUE KEY ID (ID) -- redundant
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
INSERT INTO tablesql
VALUES (1,1,5,NULL),(2,23,6,3),(3,23,7,2),(4,3,8,1),(5,3,9,2),(6,3,10,2)
, (7,3,11,3),(8,3,12,NULL),(9,4,13,NULL),(10,4,14,3);
select AccountNo, sum( case when "Charge progress" is null
then 0 else amount end ) as amount
from tablesql
where COALESCE("Charge progress", 1) BETWEEN 1 AND 2
group by AccountNo;
+-----------+--------+
| AccountNo | amount |
+-----------+--------+
| 1 | 0 |
| 3 | 27 |
| 4 | 0 |
| 23 | 7 |
+-----------+--------+
4 rows in set (0.00 sec)
select * from resultquery;
+-----------+--------+
| AccountNo | Amount |
+-----------+--------+
| 1 | 0 |
| 23 | 7 |
| 3 | 27 |
| 4 | 0 |
+-----------+--------+
4 rows in set (0.00 sec)
答案 2 :(得分:0)
我提出了一个似乎有效的尴尬,复杂的解决方案
SELECT AccountNo
,SUM(Amount
)AS Charged FROM(SELECT AccountNo
,Amount
AS AllCharges,IF(Charge progress
< 3,{{ 1}},0)AS金额来自Amount
。testsql
WHERE tablesql
介于3和4之间或AccountNo
= 23)AS xyz GROUP BY AccountNo
; < / p>
在我的评论中查看我的测试数据库。
可能有一个更简单,更优雅的解决方案,我很想看到它。
再次感谢那些已经回复了我的帮助请求的人
jankom