我的条款中有问题。我想比较具有相同Bid但具有不同sens字段的两个sum 我得到了这个输出:
SELECT v.bid
FROM v1 v
WHERE sens = 'c'
GROUP BY bid
HAVING Sum(mont) < (SELECT Sum(l.mont)
FROM v1 l
WHERE sens = 'd'
AND l.bid = v.bid group by l.bid);
ERROR 1054(42S22):字段'v.bid在字段列表中未知
编辑:V1是一个视图,我使用别名l和v试图将子查询修改为主查询
对不起伙计们,谢谢大家的答案,我在原始表的专栏中遇到了问题,现在已经解决了:)
答案 0 :(得分:5)
无需从此表中选择两个,您可以使用CASE EXPRESSION
来实现此目的:
SELECT v.bid FROM v1 v
GROUP BY v.bid
HAVING SUM(CASE WHEN v.sens = 'c' THEN v.mont ELSE 0 END) <
SUM(CASE WHEN v.sens = 'd' THEN v.mont ELSE 0 END)
AND COUNT(CASE WHEN v.sens = 'c' THEN 1 END) > 0
答案 1 :(得分:3)
subselect中的别名不可见/可用,因此您获取并找不到列错误但您可以通过这种方式重构您的查询
select v.bid, t.tot
from v1 v
Join (
select bid, sum(mont) tot
from v1
where sens = 'd'
group by bid
) t on t.bid = v.bid
where v.sens = 'c'
and v.bid < tot
答案 2 :(得分:0)
我对列的可见性存在问题,因为视图声明不正确,我很抱歉:'(我觉得非常糟糕:(
脚本:
mysql> select * from op;
+------+------+------+------+
| bid | cid | sens | mont |
+------+------+------+------+
| 1 | 1 | c | 2000 |
| 1 | 1 | c | 2000 |
| 1 | 1 | c | 2000 |
| 1 | 1 | c | 2000 |
| 1 | 2 | c | 2000 |
| 1 | 3 | c | 2000 |
| 2 | 3 | c | 2000 |
| 1 | 1 | d | 2000 |
| 2 | 3 | d | 4000 |
+------+------+------+------+
9 rows in set (0.00 sec)
create view v1 as ( select bid , cid , sens , sum(mont) as sumcli from op group by bid,cid,sens);
mysql> select * from v1 ;
+------+------+------+--------+
| bid | cid | sens | sumcli |
+------+------+------+--------+
| 1 | 1 | c | 8000 |
| 1 | 1 | d | 2000 |
| 1 | 2 | c | 2000 |
| 1 | 3 | c | 2000 |
| 2 | 3 | c | 2000 |
| 2 | 3 | d | 4000 |
+------+------+------+--------+
6 rows in set (0.00 sec)
mysql> SELECT v.bid
-> FROM v1 v
-> WHERE sens = 'c'
-> group by v.bid
-> HAVING Sum(v.sumcli) < (SELECT Sum(l.sumcli)
-> FROM v1 l
-> WHERE sens = 'd'
-> AND l.bid = v.bid group by l.bid);
+------+
| bid |
+------+
| 2 |
+------+
1 row in set (0.00 sec)