我正在尝试使用B来获取A中特定列的总和和计数,这是另一个表B.CheckerID IS NOT NULL AND A.DBDivRecID='3485'
,
所以它会得到A中的总和和数B.CheckerID IS NOT NULL A.DBDivRecID='3485'
我这样做了,但我得到了表A和B的结果,我发现两个表的DBShares列的名称相同,我只想要表A的总DBShares,只需要表B检查CheckerID
SELECT SUM(A.DBShares) As totalshares,COUNT(*) As totalcounts
FROM ShrDivBenf As A
INNER JOIN TEMPDRP_3485 AS B ON A.DBDivRecID=B.DBDivRecID
WHERE B.CheckerID IS NOT NULL AND A.DBDivRecID='3485'
我想要这样的东西(表B中的WHERE CheckerID不为空)
SELECT SUM(A.DBShares) As totalshares,COUNT(*) As totalcounts
FROM ShrDivBenf As A
WHERE CheckerID IS NOT NULL
样品
表A
+------------+----------+-------+
| DBDivRecID | DBShares |Name |
+------------+----------+-------+
| 3485 | 5000 |John |
| 3485 | 6000 |Mary |
| 3485 | 7000 |Sam |
+------------+----------+-------+
表B
+------------+-----------+----------+--------+
| DBDivRecID | CheckerID | DBShares | DBName |
+------------+-----------+----------+--------+
| 3485 | 4555 | 5000 | John |
| 3485 | 4555 | 6000 | Mary |
| 3485 | 4555 | 7000 | Sam |
| 3485 | NULL | 8000 | Derek |
+------------+-----------+----------+--------+
让我们说如果我这样做
SELECT A.DbName, A.DbShares
FROM ShrDivBenf As A
INNER JOIN TEMPDRP_3485 AS B ON A.DBDivRecID=B.DBDivRecID
WHERE B.CheckerID IS NOT NULL AND A.DBDivRecID='3485'
我会得到这个(它重复整个事情,即使我的数据库只有1个John,Mary和Sam)
+----------+----------+
| DbName | DBShares |
+----------+----------+
| John | 5000 |
| Mary | 6000 |
| Sam | 7000 |
| John | 5000 |
| Mary | 6000 |
| Sam | 7000 |
+----------+----------+
答案 0 :(得分:0)
由于您有多行具有相同的DBDivRecID
,因此您在加入时会获得笛卡尔积。避免这种情况的一种方法是将join
替换为in
运算符:
SELECT SUM(A.DBShares) As totalshares, COUNT(*) As totalcounts
FROM ShrDivBenf
WHERE DBDivRecID='3485' AND
DBDivRecID IN (SELECT DBDivRecID
FROM TEMPDRP_3485
WHERE CheckerID IS NOT NULL)
答案 1 :(得分:0)
我想我明白你想要的东西;你正在寻找没有空检查器的记录。鉴于此,请尝试以下方法:
SELECT SUM(A.DBShares) As totalshares, COUNT(*) As totalcounts
FROM ShrDivBenf
WHERE DBDivRecID='3485' AND
DBDivRecID NOT IN (SELECT DBDivRecID
FROM TEMPDRP_3485
WHERE CheckerID IS NULL)