按参数将数据放入范围

时间:2019-03-21 19:22:48

标签: sql sql-server-2008 range

我有这样的数据:

FIELD_ID | Acreage | Association
017-8596 | 1.2589  | ABC
017-8521 | 25.89   | CDA

我想首先获得Acreage s范围内的字段数:

1-10
11-25
26-50
51-100
100-500

然后通过Association得到相同的范围。

结果应如下所示:

Acreage Range | Number of Fields
1-10          | 200
11-25         | 670
25-50         | 12

第一个结果应带有对所有Association的查询,然后另一个应该是单个Association的结果。

3 个答案:

答案 0 :(得分:0)

    select qq.range_id,
           count(distinct of qq.field_id or qq.assocuation)
    from
    (
        select <all of your fields>,
               case 
                  when .... '1-10'
                  when .... '11-20'
               end range_id
        from ...
    ) qq
    group by qq.range_id

答案 1 :(得分:0)

您可以使用UNION ed子查询来声明一系列范围,然后JOIN将其与表一起使用,通过聚合来计算出现的次数:

SELECT
    CONCAT(r.lbound, '-', r.ubound) Acreage_Range, 
    COUNT(*) Number_of_Fields
FROM
    mytable t
    INNER JOIN (
        SELECT 1 lbound, 10 ubound
        UNION ALL SELECT 11, 25
        UNION ALL SELECT 26, 50
        UNION ALL SELECT 51, 100
        UNION ALL SELECT 101, 500
    ) ranges r
    ON t.acreage >= r.lbound AND t.acreage <= r.ubound
GROUP BY r.lbound, r.ubound

如果您需要过滤给定Association的结果,则只需在查询中添加WHERE子句即可。

答案 2 :(得分:0)

我尝试了这个并获得了结果,但是想知道为什么如果我的所有行都无效并且都具有数据,我却获得无效的面积。知道会触发什么吗?

     WITH AcreageData as
(
  SELECT [FIELD_ID], 
     [ASSN],
     [ACREAGE] AS ACREAGE
  FROM dbo.CaneParcel    


),
GroupAcreage AS
(
  SELECT [FIELD_ID],      
     CASE                      
         WHEN ACREAGE <= 0.50 THEN '< 0.5 Acre'
         WHEN ACREAGE >= 0.50 AND ACREAGE <= 1.01 THEN '0.5 - 1 Acre'
         WHEN ACREAGE >= 1.01 AND ACREAGE <= 10.01 THEN '1 - 10 Acres'
         WHEN ACREAGE >= 10.01 AND ACREAGE <= 25.01 THEN '10 - 25 Acres'         
         WHEN ACREAGE >= 25.01 AND ACREAGE <= 50.01 THEN '25 - 50 Acres'
         WHEN ACREAGE BETWEEN 51.01 AND 100 THEN '51 - 100 Acres'
         WHEN ACREAGE BETWEEN 101 AND 200 THEN '101 - 200 Acres'
         WHEN ACREAGE BETWEEN 201 AND 300 THEN '201 - 300 Acres'         
         WHEN ACREAGE > 1000 THEN '1000 and Over'
         ELSE 'Invalid Acreage'
     END AS [Acreage Groups]
  FROM AcreageData
)
SELECT
[Acreage Groups],
COUNT([FIELD_ID]) as NumberofParcels   
FROM GroupAcreage
GROUP BY [Acreage Groups]
ORDER BY [Acreage Groups] ASC;