0
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

It is working f9, But the problem is that the pimg_mid1 column contains same entries (every row regarding the pimg_mid1 column contains same data)

can any one tell me abt this error and the solution ???

4

1 回答 1

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 上示例。

于 2012-10-14T21:15:54.863 回答