子查询在group by子句中返回多行 - MySQL

时间:2017-06-06 02:58:06

标签: mysql sql select join group-by

我尝试使用每个日期的正确金额总和来获取我的查询结果,但是,当金额检测到相同的ID时,金额会不断累加。我希望按日期分组。不幸的是,当我运行我的查询时,它会收到一条错误,指出子查询返回超过1行

这是我的疑问:

 SELECT a.DOB as `DATE`, (CASE when f.INHOUR > 12 or f.INHour = 12 Then 'PM' 
else 'AM' END) as Shift, concat(b.FIRSTNAME, ' ', b.LASTNAME) Fullname, 
a.Amount as DECLARED, SUM(c.Amount) as CALCULATED, 
a.AMOUNT as `NET OF SPECIAL SALES`, 
d.Amount as `CASH OVER SHORT`,
a.AMOUNT as `CASH DEPOSIT`,
(SELECT SUM(gndrevn.AMOUNT) from gndrevn where gndrevn.ID= b.ID and 
gndrevn.type = "4" group by gndrevn.DOB, gndrevn.ID) as `TRANSACTION COUNT (POS)`
FROM gndsale a 
INNER JOIN emp b ON a.ID= b.ID 
INNER JOIN gndsale c ON b.ID= c.ID
INNER JOIN gndsale d on b.ID = d.ID
INNER JOIN adjtime f on a.ID= f.ID
WHERE a.type = "22" AND c.type = "4" AND d.type = "42" and 
STR_TO_DATE(a.DOB, '%m/%d/%Y') BETWEEN '2017-05-01' AND '2017-05-31' GROUP BY DECLARED 
order by STR_TO_DATE(a.DOB, '%m/%d/%Y')

它返回此错误:

enter image description here

我试图删除 gndrevn.DOB,gndrevn.ID ,这是我的结果

enter image description here

交易计数POS 刚刚添加,因为它在表中检测到类似的ID。

我想要的Transaction Count POS的结果是:

enter image description here

我使用不同的查询运行此命令,但它还需要在select语句中使用group by

以下是查询:

SELECT ID as `EMPLOYEE`, sum(AMOUNT) as AMOUNT, DOB as DATE from gndrevn 
where ID in (select ID from gndsale) and type = "4" group by 
DOB, ID order by STR_TO_DATE(DOB, '%m/%d/%Y')

我认为我的group by语句有问题需要查询。有人可以帮我吗? :(

1 个答案:

答案 0 :(得分:1)

我认为你想要的是从GROUP BY中删除gndrevn.DOB并在WHERE中添加gndrevn.DOB = a.DOB。