0

我想在自定义范围内选择 [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
4

2 回答 2

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

这样的东西。祝你好运。

于 2013-02-14T01:26:29.690 回答
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。

于 2013-02-14T01:32:02.483 回答