2017-05-15 62 views
0

我有以下表格:基於在第二表中定義的範圍內選擇值

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場(額定值1,...,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

請考慮在格式化文本中添加樣本表數據和預期結果。 同時向我們展示您當前的查詢嘗試 – TheGameiswar

+0

請參閱知道的鏈接,如何提出完美的問題:https://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-上一個公開論壇/ – TheGameiswar

回答

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 
相關問題