使用SQL显示帐户语句格式

时间:2014-08-11 06:21:47

标签: sql

我想以帐户语句格式排列数据,但我完全不知道编写SQL命令,尤其是日期范围。

表A

Creditors name       Invoice No         Due date          Outstanding Amt
88 Food Center       A001              1/8/2014            1500
24 Hours Clinic      A002              1/6/2014             300
24 Hours Clinic      A003              1/7/2014             900
24 Hours Clinic      A004              5/7/2014              50        
High Tech            A005              31/12/2014           200

结果,发言日期:2014年11月8日

Creditors name    0-30 Days    31-60 Days   61-90 Days   Over 90 Days   Amt Due        
88 Food Center      1500           0           0              0           1500
24 Hours Clinic       0           950          300            0           1250
High Tech             0            0           0             200           200

请帮助&谢谢

1 个答案:

答案 0 :(得分:1)

可能是这样的

SELECT *,`0-30 DAYS` + `31-60 DAYS` + `61-90 DAYS` + `OVER 90 DAYS` AS Amt_Due
FROM
(
  SELECT CREDITORS_NAME,
       SUM(CASE WHEN DAYS BETWEEN 0 AND 30 THEN OUTSTANDING_AMT ELSE 0 END)`0-30 Days`,
       SUM(CASE WHEN DAYS BETWEEN 31 AND 60 THEN OUTSTANDING_AMT ELSE 0 END)`31-60 Days`,
       SUM(CASE WHEN DAYS BETWEEN 61 AND 90 THEN OUTSTANDING_AMT ELSE 0 END)`61-90 Days`,
       SUM(CASE WHEN DAYS > 90 THEN OUTSTANDING_AMT ELSE 0 END) `Over 90 Days`
  FROM
  (
     SELECT Creditors_name,Invoice_No,DATEDIFF(CURDATE(),Due_date)As Days,Outstanding_Amt
     FROM Table1
  ) Tmp
  GROUP BY CREDITORS_NAME
) A

<强> FIDDLE DEMO


输出

+----------------+-------------+------------+------------+--------------+---------+
| CREDITORS_NAME | 0-30 DAYS   | 31-60 DAYS | 61-90 DAYS | OVER 90 DAYS | AMT_DUE |
+----------------+-------------+------------+------------+--------------+---------+
| 24 Hours Clinic| 0           | 50         | 1200       | 0            | 1250    |
| 88 Food Center | 1500        | 0          | 0          | 0            | 1500    |
| High Tech      | 0           | 0          | 0          | 200          | 200     |
+----------------+-------------+------------+------------+--------------+---------+