在SQL Server中随机排序

时间:2016-05-04 12:00:50

标签: sql-server sql-server-2008 sql-server-2012 sql-server-2008-r2

我使用此查询获取数据:

enter image description here

SELECT PT.ID AS ProductTypeId,
       PT.ProductType,
       PTPS.ID AS AssetId,
       PTPS.Ordinal AS AssetOrdinal,
       CASE
           WHEN PTPS.LinkType = 2
               THEN
               --DS.ServerRootURL + 'Videos/ProductTypes/' +
               --PTPSMaterialImage.LinkURL
               (
                   SELECT TOP 1 LinkURL
                   FROM ProductTypesPblmSolutions
                   WHERE ProductTypeId = PT.ID
                       AND LinkType = 1
                   ORDER BY ID DESC
               )
           ELSE PTPS.LinkURL
       END AS MaterialImage,
       ATL.LinkType
FROM ProductTypes PT
INNER JOIN ProductTypesToApps PTA ON PT.ID = PTA.ProductTypeId
INNER JOIN ProductTypesPblmSolutions PTPS ON PTPS.ProductTypeId = PT.ID
INNER JOIN DealerSettings DS ON DS.DealerId = 23
INNER JOIN AttachmentLinkTypes ATL ON ATL.ID = PTPS.LinkType
WHERE PTA.AppId = 3
    AND (PT.ID = 202 OR 202 IS NULL)
    AND (ISNULL(PTPS.IsDeleted, 0) = 0)
ORDER BY PTPS.Ordinal

让我们谈谈materialimage专栏。我必须为此产品类型获得两个不同的图像,但现在我得到相同的产品。

此产品存在许多链接。请参考下面的查询及其数据。

SELECT ProductTypeId,
       linkurl,
       linktype
FROM ProductTypesPblmSolutions
WHERE ProductTypeId = 202
    AND linktype = 1

enter image description here

我在主查询

中使用它作为子查询

如何在此列中获取不同的图像。

我尝试使用TOP 1 ... ORDER BY NEWID(),但它不起作用。

2 个答案:

答案 0 :(得分:2)

为了清楚起见,子查询应该如下所示:

            (SELECT TOP 1 ptps2.LinkURL
             FROM ProductTypesPblmSolutions ptps2
             WHERE ptps2.ProductTypeId = PT.Id AND
                   ptps2.LinkType = 1
             ORDER BY NEWID()
            )

请注意使用合格的列名称和NEWID()中的ORDER BY

我建议始终使用合格的列名。在相关子查询中,这是尤其 true,其中容易出错并且很难找到(尽管在这种特殊情况下可能不是问题)。

如果您认为没有效果,那么我会假设正在执行else的{​​{1}}组件,而不是子查询。

答案 1 :(得分:1)

SELECT TOP(1) t.LinkURL
FROM dbo.ProductTypesPblmSolutions t
WHERE t.ProductTypeId = PT.ID
    AND t.LinkType = 1
ORDER BY NEWID(), PT.ID -- additional calculation

示例#1:

SELECT TOP(10) s.number, (
    SELECT TOP(1) s1.number
    FROM [master].dbo.spt_values s1
    WHERE s1.[type] = s.[type]
    ORDER BY NEWID()
)
FROM [master].dbo.spt_values s
WHERE s.[type] = 'P'

输出:

----------- -----------
0           844
1           844
2           844
3           844
4           844
5           844
6           844
7           844
8           844
9           844

示例#2:

SELECT TOP(10) s.number, (
    SELECT TOP(1) s1.number
    FROM [master].dbo.spt_values s1
    WHERE s1.[type] = s.[type]
    ORDER BY NEWID(), s.[type] -- <<<< additional calculation
)
FROM [master].dbo.spt_values s
WHERE s.[type] = 'P'

输出:

----------- -----------
0           428
1           801
2           550
3           1619
4           178
5           17
6           1702
7           683
8           352
9           1844