sql查询无法正常工作(关于选择随机记录)

时间:2012-10-14 21:08:56

标签: sql sql-server

USE [cms]
GO
/****** Object:  StoredProcedure [dbo].[SpCateProductsInfo]    Script Date: 10/14/2012 00:50:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[SpCateProductsInfo](@cate_id int)
as
begin
select sb.subcate_name, sum(p.qty) as totalqty, 
(select top 1 pimg_mid1 from product join subcategory
on product.subcate_id=
(
    select top 1 subcate_id
    from subcategory
    where cate_id=@cate_id
    order by NEWID()
)
order by NEWID()) as pimg_mid1
from subcategory sb 
  join product p on p.subcate_id = sb.subcate_id
where sb.cate_id = @cate_id
group by sb.subcate_name


end

它正在运行f9,但问题是pimg_mid1列包含相同的条目(关于pimg_mid1列的每一行包含相同的数据

任何人都可以告诉我这个错误和解决方案???

1 个答案:

答案 0 :(得分:1)

由于pimg_mid1基于:

SELECT TOP 1 PIMG_MID1 
FROM   PRODUCT 
       JOIN SUBCATEGORY 
         ON PRODUCT.SUBCATE_ID = (SELECT TOP 1 SUBCATE_ID 
                                  FROM   SUBCATEGORY 
                                  WHERE  CATE_ID = @cate_id 
                                  ORDER  BY Newid()) 
ORDER  BY Newid() 

并且此子查询不受其附加的单个行的影响,它将始终返回相同的结果。

“正确”的方式是这样的:

SELECT t1.COLA, 
       T1.COLB, 
       T2.COLZ 
FROM   (SELECT *, 
               Row_number() 
                 OVER ( 
                   ORDER BY COLA) RN 
        FROM   MAIN)T1 
       INNER JOIN(SELECT COLZ, 
                         Row_number() 
                           OVER ( 
                             ORDER BY Newid()) RN 
                  FROM   RANDOM)T2 
               ON T1.RN = T2.RN 

请参阅SQL Fiddle上的示例here