我有一个像这样设计的表:
tbl_User
id
Name
tbl_User_Payment
id
user_id
amount
status
tbl_User
id Name
001 John Doe
002 Juan Dela Cruz
tbl_User_Payment
id user_id amount status
001 001 10 Successful
002 002 10 Fail
003 001 10 Fail
004 001 10 Fail
005 001 10 Fail
006 002 10 Successful
007 002 10 Fail
008 002 10 Fail
这里的问题是,如何在成功付款后计算失败付款的数量。 所以这里的结果应该是这样的:
John Doe - 3 Failed Payment
Juan Dela Cruz - 2 Failed Payment
我希望你能理解我在这里要完成的事情。
您的帮助将受到极大的赞赏和奖励!
谢谢! :)
答案 0 :(得分:1)
为了简洁明了,我会在代码中添加一些内容。
SELECT
Users.UserName,
FailCount
FROM
(
SELECT
UserId,
COUNT(*) As FailCount
FROM
Payments,
(
SELECT
UserId,
MAX( PaymentId ) As LastSuccessId
FROM
Payments
WHERE
Status = Successful
GROUP BY
UserId
) AS LastSuccess
WHERE
PaymentId > LastSuccessId
GROUP BY
UserId
) As FailCount
INNER JOIN Users ON Users.UserId = FailCount.UserId
ORDER BY
UserName DESC
I&#39; MA位生锈,我避难所&#39;吨测试此SQL,但如果它不&#39;吨工作我怀疑它&#39; S因为我&#34; FROM Payments, <subquery>
&# 34;句法。我没有能够验证我的解决方案,所以如果它不起作用,你可能需要招募一些人来帮助你。
如果你想知道,这就是我的逻辑:
SELECT
)上次成功付款的ID。COUNT
行,这些行是在&#34;最后一次成功的付款ID&#34;由最里面的SELECT
检索的值。JOIN
第3步中使用users表获取用户名的结果。此外,未来数据库设计的一些提示:在数据库设计中不需要使用匈牙利表示法 - 每次看到&#34; tbl _&#34;前缀。我还建议不要简单地命名主键字段&#34; id&#34;因为它需要消除歧义,因此它使JOIN变得更加困难。考虑在前面加上表格的名称(例如&#34; payments.id
&#34;变为&#34; Payments.PaymentId
&#34;)。
答案 1 :(得分:1)
尝试使用count函数和group by语句
例如:
select Name, count(Status), Status from tbl_User as tu, tbl_User_Payment as tup where tup.user_id = tu.id group by status
检查一下,如果有帮助,请告诉我。
答案 2 :(得分:1)
尝试此查询
SELECT
`user_id`,
COUNT(id) AS "Total",
SUM(CASE WHEN status= 'Fail' THEN 1 ELSE 0 END) AS "Failed",
SUM(CASE WHEN status= 'Successful' THEN 1 ELSE 0 END) AS "Successful"
FROM `tbl_User_Payment`
GROUP BY `user_id`;
答案 3 :(得分:-1)
PHP版本。这可以进行优化,以便它不会遍历user
表中的每个tbl_User
/行,但它可以完成工作。
<?php
$mysqli = new mysqli('localhost', 'root', DB_PASSWORD, DB_NAME);
if ($mysqli->connect_error)
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
$result = $mysqli->query("SELECT * FROM `tbl_User_Payment` WHERE `status` = 'Fail'"))
$array = [];
while ($col = $result->fetch_array(MYSQLI_ASSOC)) {
if (array_key_exists($col['user_id'], $array))
$array[$col['user_id']] = $array[$col['user_id']]+1;
else
$array[$col['user_id']] = 1;
}
$result->close();
$mysqli->close();
$mysqli = new mysqli('localhost', 'root', DB_PASSWORD, DB_NAME);
if ($mysqli->connect_error)
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
$result = $mysqli->query("SELECT * FROM `tbl_User` WHERE 1"))
while ($col = $result->fetch_array(MYSQLI_ASSOC)) {
if (array_key_exists($col['id'], $array))
echo $col['Name'] . ' - ' . $array[$col['id']] . ' Failed attempts <br />';
}
$result->close();
$mysqli->close();
?>