任何人都可以帮助我,如果我输入“ GROUP BY DATE”,为什么该代码不起作用
DATE的样本值为201810、201811、201812、201901等
如果我删除“ GROUP BY DATE”,则它的工作将对所有行求和 我想要按日期列出所有省份的SUM totaluser组,有什么想法吗?
SELECT DATE AS dates,
parProvinces.id AS provinceId,
parProvinces.name AS province,
sum(totaluser) AS countUser,
( SELECT
SUM(totalUser)
FROM dsMonthlyDemographies
GROUP BY DATE // <<<<-- this is didn't
) AS totalUserPerMonths
FROM dsMonthlyDemographies, parProvinces
WHERE (provincesId = parProvinces.id)
GROUP BY provinceId, dates
ORDER BY dates ASC, provinceId ASC
消息错误:
错误代码:1242 子查询返回1行以上
更新
这是dsMonthlyDemographies的示例数据
表parProvinces
答案 0 :(得分:1)
您需要一个标量子查询
SELECT DATE AS dates,
parProvinces.id AS provinceId,
parProvinces.name AS province,
sum(totaluser) AS countUser,
( SELECT
SUM(totalUser)
FROM dsMonthlyDemographies b where a.date=b.date
) AS totalUserPerMonths
FROM dsMonthlyDemographies a join parProvinces on a.provincesId = parProvinces.id
GROUP BY provinceId, dates
ORDER BY dates ASC, provinceId ASC
OR
select * from
(SELECT DATE AS dates,
parProvinces.id AS provinceId,
parProvinces.name AS province,
sum(totaluser) AS countUser
FROM dsMonthlyDemographies a join parProvinces on a.provincesId =parProvinces.id
GROUP BY provinceId, dates
)A inner join
( SELECT
dates,SUM(totalUser)
FROM dsMonthlyDemographies group by dates
) AS B on A.dates=b.dates
注意:最好总是使用显式联接,而不是用逗号分隔的联接
答案 1 :(得分:1)
您的朋友,您只需添加b.provincesId = dsMonthlyDemographies.provincesId
,如下所示:
SELECT DATE AS dates,
parProvinces.id AS provinceId,
parProvinces.name AS province,
sum(totaluser) AS countUser,
( SELECT
SUM(b.totalUser)
FROM dsMonthlyDemographies b
b.provincesId = dsMonthlyDemographies.provincesId
) AS totalUserPerMonths
FROM dsMonthlyDemographies, parProvinces
WHERE (provincesId = parProvinces.id)
GROUP BY provinceId, dates
ORDER BY dates ASC, provinceId ASC