我试图查询过去36个月内已经开立的贷款清单。我还试图将过去12个月内已经开立的贷款数量作为一个单独的列进行查询。
查询为两列返回相同的值,如何在不运行单独查询的情况下从36个月和12个月的间隔获取计数?
SELECT
`XDL-NAME`,
COUNT(distinct`XLN-LOANDATE`) as '36 Month Count',
COUNT(IF(`XLN-LOANDATE` >= DATE_SUB(NOW(),INTERVAL 12 MONTH), 1 , NULL)) AS '12 Month Count'
from
LOAN
JOIN
DEALER ON `XLN-DLNO` = `XDL-NUM` WHERE `XLN-LOANDATE` >= DATE_SUB(NOW(),INTERVAL 36 MONTH)
GROUP BY `XDL-NAME`
答案 0 :(得分:0)
而不是count
代替12 months
,更改为sum
,如下所示
SELECT
`XDL-NAME`,
COUNT(distinct`XLN-LOANDATE`) as '36 Month Count',
SUM(IF(`XLN-LOANDATE` >= DATE_SUB(NOW(),INTERVAL 12 MONTH), 1 , 0)) AS '12 Month Count'
from
LOAN
JOIN
DEALER ON `XLN-DLNO` = `XDL-NUM` WHERE `XLN-LOANDATE` >= DATE_SUB(NOW(),INTERVAL 36 MONTH)
GROUP BY `XDL-NAME`
答案 1 :(得分:0)
试试这个:
SELECT
`XDL-NAME`,
count((SELECT `XLN-LOANDATE` WHERE `XLN-LOANDATE` >= DATE_SUB(NOW(),INTERVAL 36 MONTH))) AS '36 Month Count',
count((SELECT `XLN-LOANDATE` WHERE `XLN-LOANDATE` >= DATE_SUB(NOW(),INTERVAL 12 MONTH))) AS '12 Month Count',
from
LOAN
JOIN
DEALER ON `XLN-DLNO` = `XDL-NUM`
GROUP BY `XDL-NAME`
我所做的是使用子查询来计算您想要的每个间隔。通过这种方式,他们应该输出名称,36个月计数,12个月计数全部在一行(记录)。
答案 2 :(得分:0)
我希望此查询返回两个单独的计数:
SELECT `XDL-NAME`,
COUNT(*) as `36 Month Count`,
SUM(`XLN-LOANDATE` >= DATE_SUB(NOW(), INTERVAL 12 MONTH)) AS `12 Month Count`
FROM loan l join
dealer d
ON `XLN-DLNO` = `XDL-NUM`
WHERE `XLN-LOANDATE` >= DATE_SUB(NOW(), INTERVAL 36 MONTH)
GROUP BY `XDL-NAME`;
答案 3 :(得分:0)
尝试 SUM ,如:
SUM(IF('2016-12-21' >= NOW() -INTERVAL 12 MONTH, 1, 0)) AS '12 Month Count'
<强>示例强>
mysql> SELECT IF('2016-12-21' >= NOW() -INTERVAL 12 MONTH, 1, 0);
+----------------------------------------------------+
| IF('2016-12-21' >= NOW() -INTERVAL 12 MONTH, 1, 0) |
+----------------------------------------------------+
| 1 |
+----------------------------------------------------+
1 row in set (0,00 sec)
mysql> SELECT IF('2015-12-22' >= NOW() -INTERVAL 12 MONTH, 1, 0);
+----------------------------------------------------+
| IF('2015-12-22' >= NOW() -INTERVAL 12 MONTH, 1, 0) |
+----------------------------------------------------+
| 1 |
+----------------------------------------------------+
1 row in set (0,00 sec)
mysql> SELECT IF('2015-12-21' >= NOW() -INTERVAL 12 MONTH, 1, 0);
+----------------------------------------------------+
| IF('2015-12-21' >= NOW() -INTERVAL 12 MONTH, 1, 0) |
+----------------------------------------------------+
| 0 |
+----------------------------------------------------+
1 row in set (0,00 sec)
mysql>