选择列值在预定义范围内出现的频率

时间:2013-02-14 01:14:20

标签: sql-server tsql

我想在自定义范围内选择[price]字段的值出现次数:

我的价格范围是:

< 10  
10-20  
20-50  
> 50  

因此,如果价格为3,4,11和20,结果将是:

< 10 (2)  
10-20 (1)  
21-50 (1)  
> 50 (0) 

以下是表格定义:

CREATE TABLE [dbo].[products](
[id] [int] IDENTITY(1,1) NOT NULL,
[price] [decimal](8, 0) NULL,
[createdate] [datetime] NOT NULL,
CONSTRAINT [PK_products] PRIMARY KEY CLUSTERED 
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[products] ADD  CONSTRAINT [DF_products_createdate]  DEFAULT (getdate()) FOR [createdate]
GO

2 个答案:

答案 0 :(得分:1)

With 
Categorized as
(
 Select 
 CASE When Price < 10 Then '<10'
      When Price >= 10 and Price < 20 Then '[10-20)'
      Else '>20'
 END as Category
 From SomeTable
)
Select Category, Count(*) From Categorized
Group By Category

喜欢这个。祝你好运。

答案 1 :(得分:0)

你可以这样做。

;WITH Ranges_CTE ([sequence], [range], [lower_limit], [upper_limit]) AS
  (
   SELECT 1,'<10', 0, 9
    UNION
    SELECT 2,'10-20', 10, 19
    UNION
    SELECT 3, '20-50', 20, 50
    UNION
    SELECT 4, '>50', 51, 1000
   )

SELECT r.range, count(p.id) AS ROW_COUNT
FROM ranges_cte r
LEFT OUTER JOIN products p ON p.price BETWEEN r.lower_limit AND r.upper_limit
GROUP BY r.range, r.sequence
ORDER BY r.sequence

请注意,您的范围不明确。您在一个地方展示20-50,在其他地方展示21-50。数据似乎表明20-50是正确的。但是,价格20适合10-2020-50。我假设10-20的上限为19。