我有一张看起来像这样的表,
+-----+--------+-------+
| 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 |
+-----+--------+-------+
我想总结一下“数量”'基于不同数字的列#39;列'值'等于1, 例如,在运行以下查询后,
select DISTINCT num, amount, value from test where value =1 ;
distinct' 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');
答案 0 :(得分:0)
select num,sum(amount)/Count(*)
from test
where value = 1
group by num
order by num
答案 1 :(得分:0)
我假设每个num都有相同的值(如果没有,你应该如何选择一个?)
所以,这将有效:
SELECT SUM(DISTINCT amount)
FROM test
WHERE value = 1
答案 2 :(得分:0)
SELECT SUM(amount) FROM (SELECT DISTINCT num, amount, VALUE FROM test WHERE VALUE =1) AS temp ;
答案 3 :(得分:0)
您可以创建包含不同值的临时表,并使用SUM()
计算金额。您的查询将如下:
SELECT SUM(amount)
FROM (
SELECT DISTINCT t.`num`, t.`amount`
FROM test t
WHERE t.`value`=1
) temp
答案 4 :(得分:0)
请检查解决方案
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