[英]Mysql get sum of column_1 based on distinct value in column_2
[英]Mysql - Get Sum of All distinct rows based on other value
我有一張看起來像這樣的桌子,
+-----+--------+-------+
| num | amount | value |
+-----+--------+-------+
| 1 | 12 | 1 |
| 1 | 12 | 1 |
| 2 | 13 | 1 |
| 4 | 15 | 0 |
| 2 | 13 | 1 |
| 3 | 14 | 1 |
| 3 | 14 | 1 |
| 1 | 12 | 1 |
+-----+--------+-------+
我想根據不同的'num'列對'amount'列求和,其中'value'等於1,例如,在運行以下查詢后,
select DISTINCT num, amount, value from test where value =1 ;
基於不同'num'的表是
+-----+--------+-------+
| num | amount | value |
+-----+--------+-------+
| 1 | 12 | 1 |
| 2 | 13 | 1 |
| 3 | 14 | 1 |
+-----+--------+-------+
所以我想要最終結果
12 + 13 + 14 = 39。
還有一件事就是
我不能使用子查詢。
因為它已經是另一個查詢的一部分。
這是我表的腳本是
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `test`
-- ----------------------------
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
`num` int(11) DEFAULT NULL,
`amount` int(11) DEFAULT NULL,
`value` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of test
-- ----------------------------
INSERT INTO `test` VALUES ('1', '12', '1');
INSERT INTO `test` VALUES ('1', '12', '1');
INSERT INTO `test` VALUES ('2', '13', '1');
INSERT INTO `test` VALUES ('4', '15', '0');
INSERT INTO `test` VALUES ('2', '13', '1');
INSERT INTO `test` VALUES ('3', '14', '1');
INSERT INTO `test` VALUES ('3', '14', '1');
INSERT INTO `test` VALUES ('1', '12', '1');
select num,sum(amount)/Count(*)
from test
where value = 1
group by num
order by num
我假設每個num都有相同的值(如果沒有,你應該如何選擇一個?)
所以,這將工作:
SELECT SUM(DISTINCT amount)
FROM test
WHERE value = 1
SELECT SUM(amount) FROM (SELECT DISTINCT num, amount, VALUE FROM test WHERE VALUE =1) AS temp ;
您可以創建包含不同值的臨時表,並使用SUM()
計算金額。 您的查詢將如下所示:
SELECT SUM(amount)
FROM (
SELECT DISTINCT t.`num`, t.`amount`
FROM test t
WHERE t.`value`=1
) temp
請檢查解決方案
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `test`
-- ----------------------------
DROP TABLE IF EXISTS `test`;
CREATE TABLE `test` (
`num` int(11) DEFAULT NULL,
`amount` int(11) DEFAULT NULL,
`value` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of test
-- ----------------------------
INSERT INTO `test` VALUES ('1', '12', '1');
INSERT INTO `test` VALUES ('1', '12', '1');
INSERT INTO `test` VALUES ('2', '13', '1');
INSERT INTO `test` VALUES ('4', '15', '0');
INSERT INTO `test` VALUES ('2', '13', '1');
INSERT INTO `test` VALUES ('3', '14', '1');
INSERT INTO `test` VALUES ('3', '14', '1');
INSERT INTO `test` VALUES ('1', '12', '1');
-- ----------------------------
-- Insert the result set into temp table and then use sum().
-- ----------------------------
SELECT DISTINCT `num` , `amount`
INTO #tmp
FROM test
WHERE `value` =1
SELECT * FROM #tmp
SELECT sum(`amount`) as amount FROM #tmp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.