// thinkphp5.1 查询7天内每天的金额总数
$dates = [];
for ($i=7; $i >= 0; $i--) { // 近7天日期
$dates[] = date('Y-m-d', strtotime('-'.$i.' days'));
}
$where = " where unix_timestamp(time) >= unix_timestamp('".$dates[0]."')";
$order = " group by date_format(time, '%Y-%m-%d')";
$select = "select date_format(time, '%Y-%m-%d') as time,sum(money) as count from czjl";
$sql = $select.$where.$order;
$orderList = Db::query($sql);
dump($orderList);
数据库
结果
你可以参考下
楼主如下写即可,望采纳:
SELECT A.日期,ISNULL(B.入院人数,0) AS 入院人数,ISNULL(C.出院人数,0) AS 出院人数
FROM
(
SELECT 入院日期 AS 日期 FROM TABLE GROUP BY 入院日期
WHERE 入院日期 >= '2013-10-11' AND 出院日期 <= '2013-11-13'
UNION
SELECT 出院日期 AS 日期 FROM TABLE GROUP BY 出院日期
WHERE 入院日期 >= '2013-10-11' AND 出院日期 <= '2013-11-13'
)A
LEFT JOIN
(
SELECT COUNT(ID) AS 入院人数,入院日期 FROM TABLE GROUP BY 入院日期
)B ON B.入院日期=A.日期
LEFT JOIN
(
SELECT COUNT(ID) AS 出院人数,出院日期 FROM TABLE GROUP BY 出院日期
)C ON C.出院日期 = A.日期
select
case when a.入院日期 is null then b.出院日期 else a.入院日期 end as 时间,
case when a.入院人数 is null then 0 else a.入院人数 end as 入院人数,
case when b.出院人数 is null then 0 else b.出院人数 end as 出院人数
from
(select 入院日期,count(1) as 入院人数
from tab
group by 入院日期
) a full join
(select 出院日期,count(1) as 出院人数
from tab
where 出院日期 is not null
group by 出院日期
) b on a.入院日期=b.出院日期
楼主如下写即可,望采纳:
123456789101112131415161718SELECT A.日期,ISNULL(B.入院人数,0) AS 入院人数,ISNULL(C.出院人数,0) AS 出院人数FROM( SELECT 入院日期 AS 日期 FROM TABLE GROUP BY 入院日期 WHERE 入院日期 >= '2013-10-11' AND 出院日期 <= '2013-11-13' UNION SELECT 出院日期 AS 日期 FROM TABLE GROUP BY 出院日期 WHERE 入院日期 >= '2013-10-11' AND 出院日期 <= '2013-11-13')A LEFT JOIN( SELECT COUNT(ID) AS 入院人数,入院日期 FROM TABLE GROUP BY 入院日期)B ON B.入院日期=A.日期LEFT JOIN ( SELECT COUNT(ID) AS 出院人数,出院日期 FROM TABLE GROUP BY 出院日期)C ON C.出院日期 = A.日期
SELECT NVL(T1."DATE", T2."DATE") "时间", NVL(T1.CNT1, 0) "入院人数", NVL(T2.CNT2, 0) "出院人数"
FROM (SELECT T."入院日期" "DATE", COUNT(*) CNT1
FROM "TEST" T
WHERE T."入院日期" BETWEEN TO_DATE('20131011') AND TO_DATE('20131113')
GROUP BY T."入院日期") T1
FULL JOIN (SELECT T."出院日期" "DATE", COUNT(*) CNT2
FROM "TEST" T
WHERE T."出院日期" BETWEEN TO_DATE('20131011') AND
TO_DATE('20131113')
GROUP BY T."出院日期") T2
ON T1."DATE" = T2."DATE"
ORDER BY NVL(T1."DATE", T2."DATE")
我这不是中文系统,SQL里的中文是后贴上去的,原来都是英文,保证好用