在sql server中选择单行作为多行

时间:2014-11-24 12:35:29

标签: sql asp.net sql-server stored-procedures

我不是编写SQL查询的专家。我目前想出了一个存储过程。当我还没有应用内连接时,存储过程正常。我有两张桌子。

表1:产品 表2:ProductRating

存储过程用于明智地选择记录。我通过查阅在线文章创建了这个。存储过程的主体如下所述,

SELECT ROW_NUMBER() OVER (ORDER BY [PostedDate] Desc)AS RowNumber,[Products].[Id], [Name], [Description], [PostedDate], 
           ISNULL(AVG([ProductRating].[RatingValue]), 0) AverageRating, COUNT([Rating].[RatingValue]) RatingCount
           INTO #DealResults1
           FROM [Products]
           LEFT OUTER  JOIN [Rating] ON [Product].[Id] = [Rating].[ProductId]
           WHERE [City] = CASE WHEN @CityId IS NULL THEN [City] ELSE @CityId END 
           AND [Description] IS NOT NULL  
           Group by [Products].[Id], [Name], [Description], [PostedDate], [Rating].[RatingValue]
           ORDER BY [PostedDate] Desc


           DECLARE @RecordCount1 INT
           SELECT @RecordCount1 = COUNT(*) FROM #ProductResults1

           SET @PageCount = CEILING(CAST(@RecordCount1 AS DECIMAL(10, 2)) / CAST(@PageSize AS DECIMAL(10, 2)))
           PRINT @PageCount

           SELECT * FROM #ProductResults1
           WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1

           DROP TABLE #ProductResults1

现在我承认我在加入时非常贫穷,而且我从未完全理解该组织。

问题陈述: 当用户对产品评级时,每次在评级表中插入记录。现在,如果用户将Product1评级三次,则选择Product三次。有时两次。我不明白这个问题。请帮助我。

1 个答案:

答案 0 :(得分:2)

仅按产品表中的列进行分组。你在组中添加[评级]。[RatingValue]。 例如:

Group by [Products].[Id], [Name], [Description], [PostedDate]