用于求和存储桶的SQL查询

时间:2016-07-04 17:25:40

标签: sql ms-access

我有一个包含inovices的表和一个名为Arrers天的字段,我需要计算0-30天内有多少项目也在30-90和90-120

基本上我需要的是计算我的客户组合的老化。

到目前为止,我有这个:

SELECT SUM(CASE WHEN Receivable.Arrers>'0'<'30' THEN 1 ELSE 0) AS 0-30,
       SUM(CASE WHEN Receivable.Arrers<'30'>'60' THEN 1 ELSE 0) AS 30-60, 
       SUM(CASE WHEN Receivable.Arrers<'90'>'120' THEN 1 ELSE 0) AS 90-120 
From Receivable 

表名应收款

Invoice   Arrers    
89859       10  
89856       3  
89853       11  

4 个答案:

答案 0 :(得分:1)

你可以尝试那个

SELECT 
       SUM( CASE WHEN Receivable.Arrers BETWEEN 0 AND 30 THEN 1 ELSE 0) AS '0-30',
       SUM (CASE WHEN Receivable.Arrers BETWEEN 30 AND 60 THEN 1 ELSE 0) AS '30-60',
       SUM (CASE WHEN Receivable.Arrers BETWEEN 90 AND 120 THEN 1 ELSE 0) AS '90-120',
       arrers
FROM Receivable
GROUP BY arrers

需要检查一件事。

  1. 我将BETWEEN 90 AND 120视为整数。如果它们是varchar,则需要将它们转换为整数。 Val(Receivable.Arrers)将完成访问权限。如果有任何不清楚的地方,请通知我

答案 1 :(得分:1)

除了可能的CASE stmt语法之外,你走在正确的轨道上......尝试没有Group by的Andy的回答

(没有足够的分数作为评论发布)

答案 2 :(得分:1)

我使用这样的东西:

SELECT subq.ArrersGroup, COUNT(*) 'Count'
FROM
(
SELECT
  CASE
    WHEN R.Arrers < 30 THEN '0-30'
    WHEN R.Arrers < 90 THEN '30-90'
    WHEN R.Arrers < 120 THEN '90-120'
    ELSE 'Other'
  END ArrersGroup
FROM Receivable R
) subq
GROUP BY subq.ArrersGroup

SqlFiddle

答案 3 :(得分:1)

Access SQL不支持CASE WHEN。您可以改为使用IIf表达式。

SELECT
    SUM(IIf(r.Arrers BETWEEN  0 AND  30, 1, 0)) AS [0-30],
    SUM(IIf(r.Arrers BETWEEN 31 AND  60, 1, 0)) AS [31-60], 
    SUM(IIf(r.Arrers BETWEEN 90 AND 120, 1, 0)) AS [90-120] 
FROM Receivable AS r;

您的问题中的示例忽略了Arrers从61到89,所以我也这样做了。但是如果需要,您可以添加另一个列表达式。

如果Arrers是text而不是numeric数据类型,则可以使用Val()将文本值转换为数字...

SUM(IIf(Val(r.Arrers) BETWEEN  0 AND  30, 1, 0)) AS [0-30]