我有一个数据库查询,将付款按月分组。
我现在面临的问题是,我无法看到每笔付款都能确保所有付款都已付款。
列中的dp是Date Paid。
如果列中的日期为0000-00-00 00:00:00,则表示尚未付款。
以下是查询:
$monthlyQuery = $pdo->prepare("
SELECT SUM(net) AS net
, MONTH(dd) AS month
, YEAR(dd) AS year
, dp
FROM sin WHERE cpo=:cpo
AND dd >= :dd1
AND dd <= :dd2
GROUP
BY month
ORDER
BY dd ASC
");
$monthlyQuery->execute(array(':cpo' => $fetch['cpo'], ':dd1' => $janDate, ':dd2' => $decDate));
$monthlyQueryNum = $monthlyQuery->rowCount();
有没有办法在行被分组之前检查每个dp列,如果在任何时候日期是0000-00-0000:00 00:00然后为该组生成所有日期00:00 :00
当时我正在考虑做一个案例,但逻辑似乎对我不起作用。
由于
答案 0 :(得分:0)
由于您没有向我们提供数据来测试这一点,因此我编写了以下内容而无法对其进行测试。它应该接近你想要的:
SELECT
SUM(s.net) AS net
,MONTH(s.dd) AS month
,YEAR(s.dd) AS year
,COALESCE(missing.inner_dp,s.dp) AS dp
FROM
sin s
LEFT JOIN
(
SELECT
YEAR(s2.dd) AS inner_year
,MONTH(s2.dd) AS inner_month
,cpo AS inner_cpo
,dp AS inner_dp
FROM
sin s2
WHERE
s2.dp = '0000-00-00 00:00:00'
AND s2.dd >= :dd1
AND s2.dd <= :dd2
GROUP BY
inner_year, inner_month, inner_cpo, inner_dp
) AS missing ON
YEAR(s.dd) = missing.inner_year
AND MONTH(s.dd) = missing.inner_month
AND s.cpo = missing.inner_cpo
WHERE
s.cpo=:cpo
AND s.dd >= :dd1
AND s.dd <= :dd2
GROUP BY
year, month, dp
ORDER BY
year, month, dp
我不是MySQL的粉丝,允许“隐式”GROUP BY
表达式,我已经明确表达了它们。您会注意到我也将ORDER BY
更改为您看起来有问题的那个。