根据第二个表中定义的范围选择值

时间:2017-05-15 12:43:06

标签: tsql azure-sql-database sql-server-2016

我有以下表格:

CREATE TABLE [dbo].[Ratings](
    [Id] int NOT NULL,
    [CompanyId] int NOT NULL,
    [UserId] int NOT NULL,
    [Rating] [int] NOT NULL
 CONSTRAINT [PK_dbo.Ratings] PRIMARY KEY NONCLUSTERED 
(
    [Id] ASC
)

CREATE TABLE [dbo].[RatingScales](
    [Id] int NOT NULL,
    [Rating1] [real] NOT NULL,
    [Rating2] [real] NOT NULL,
    [Rating3] [real] NOT NULL,
    [Rating4] [real] NOT NULL,
    [Rating5] [real] NOT NULL,
 CONSTRAINT [PK_dbo.RatingScales] PRIMARY KEY NONCLUSTERED 
(
    [Id] ASC
)

然后我开始:

SELECT R.CompanyId, AVG(R.Rating) AS Average
FROM Ratings AS R
GROUP BY R.CompanyId

RatingScales字段(Rating1,...,Rating5)包含每个范围的最小值:

Rating1 >= 1.2
Rating2 >= 2.3
...
Rating5 >= 4.6

我需要的是返回平均评分所在的相应范围。

例如:

CompanyId | Rating  | Average
1         | Rating1 | 1.5
2         | Rating4 | 4
3         | Rating2 | 2.8
4         | NULL    | 0

我该怎么做?

1 个答案:

答案 0 :(得分:1)

这应该适合你。

--Id from the RatingScales table that you want to use
DECLARE @ratingId INT = 1;

--Common Table Expression to get the Average
WITH avgRating AS 
    (SELECT R.CompanyId, AVG(R.Rating * 1.00) AS Average
    FROM Ratings AS R
    GROUP BY R.CompanyId)

--Determine which rating category the company is in
SELECT CompanyId,
       CASE WHEN Average >= (SELECT Rating1 FROM RatingScales WHERE Id = @ratingId) AND 
       Average < (SELECT Rating2 FROM RatingScales WHERE Id = @ratingId) THEN 'Rating1'
       WHEN Average >= (SELECT Rating2 FROM RatingScales WHERE Id = @ratingId) AND 
       Average < (SELECT Rating3 FROM RatingScales WHERE Id = @ratingId) THEN 'Rating2' 
       WHEN Average >= (SELECT Rating3 FROM RatingScales WHERE Id = @ratingId) AND 
       Average < (SELECT Rating4 FROM RatingScales WHERE Id = @ratingId) THEN 'Rating3'
       WHEN Average >= (SELECT Rating4 FROM RatingScales WHERE Id = @ratingId) AND 
       Average < (SELECT Rating5 FROM RatingScales WHERE Id = @ratingId) THEN 'Rating4' 
       WHEN Average >= (SELECT Rating4 FROM RatingScales WHERE Id = @ratingId) THEN 'Rating5'   
       ELSE NULL END 'Rating',
       CAST(Average AS decimal(3,2)) 'Average'
FROM avgRating