我有一张表,需要调用select两次,具有两个不同的where条件,然后将其放回一个。
如果我分别运行select`s,它会给我正确的结果,但是在一个具有内部联接的查询中没有选择,第二个select被加倍。
表格如下:
amount | paydate | ...
-337 | 2018-01-10 | ...
1467 | 2018-01-10 | ...
-322 | 2018-02-10 | ...
1452 | 2018-02-10 | ...
结果应为:
January | 1467 | -337
February | 1452 | -322
但是我得到
January | 1467 | -322
February | 1452 | -322
这是我的查询
SELECT
Q1.month,
Q1.ttlincome,
Q1.paydate,
Q2.ttldebid
FROM (
SELECT MONTHNAME(`paydate`) as month,
(`amount`) AS ttlincome,
paydate, propertiseid
FROM `test`
WHERE `test`.`amount` > 0
AND `test`.`paydate` BETWEEN '2018-01-01' AND '2018-12-31'
GROUP BY YEAR(`test`.`paydate`), MONTH(`test`.`paydate`)
) AS Q1
INNER JOIN (
SELECT (`amount`) AS ttldebid,
FROM `test`
WHERE `test`.`amount` < 0
AND `test`.`paydate` BETWEEN '2018-01-01' AND '2018-12-31'
GROUP BY YEAR(`test`.`paydate`), MONTH(`test`.`paydate`)
) AS Q2
GROUP BY YEAR(Q1.`paydate`), MONTH(Q1.`paydate`)
也许有更好的方法可以使它工作?
答案 0 :(得分:1)
为什么不这样做:
select monthname(paydate),
max(amount), min(amount)
from t
where paydate >= '2018-01-01' and paydate < '2019-01-01'
group by monthname(paydate)
order by min(paydate);
或者,如果您可以拥有两行以上:
select monthname(paydate),
sum(case when amount > 0 then amount end),
sum(case when amount < 0 then amount end)
from t
where paydate >= '2018-01-01' and paydate < '2019-01-01'
group by monthname(paydate)
order by min(paydate);
答案 1 :(得分:-1)
我认为您的查询应该是这样
SELECT
Q1.month,
Q1.ttlincome,
Q1.paydate,
Q2.ttldebid
FROM (
SELECT distinct MONTHNAME(`paydate`) as month,
(`amount`) AS ttlincome,
paydate, propertiseid
FROM `test`
WHERE `test`.`amount` > 0
AND `test`.`paydate` BETWEEN '2018-01-01' AND '2018-12-31'
) AS Q1
INNER JOIN (
SELECT distinct (`amount`) AS ttldebid,MONTHNAME(`paydate`) as month
FROM `test`
WHERE `test`.`amount` < 0
AND `test`.`paydate` BETWEEN '2018-01-01' AND '2018-12-31'
) AS Q2
on Q1.month=Q2.month