提取数据但包含特定记录

时间:2012-07-12 15:48:30

标签: sql sql-server sql-server-2008 tsql

我的老板给了我一个有趣的挑战。我们有一个数据集来提取页面上的某些广告客户,但如果您是登录的广告客户,他希望确保首先展示广告客户。这是现在的脚本:

SELECT TOP 15
a.MemberID,             -- 0
a.UserName,             -- 1
a.MemberDisplayName,    -- 2
a.NYKABizName           -- 3
FROM Member a
INNER JOIN AdDisplay b ON b.MemberID = a.MemberID
WHERE a.Claimed = 'Y'
AND a.NYKACatID IS NOT NULL
AND b.LocalPageID = @LocalPageID
AND a.SBIcon = 'N'
AND a.Viewable = 'Y'
AND a.ProfileTypeID <> 1
AND a.PackageType <> 'G'
AND a.PackageType <> 'P'
AND a.PackageType <> 'C'
ORDER BY PackageType ASC

我想添加一些像Include MemberID = 102.如何更改此脚本以完成老板的愿望。

非常感谢,

neojakey

3 个答案:

答案 0 :(得分:4)

假设查询返回有问题的广告商(没有前15名),您可以通过修改order by子句来执行此操作:

order by (case when MemberId = 102 then 0 else 1 end),
         PackageType ASC

这将命令列表首先放置所需的成员,然后是其他所有成员。您仍然可以在查询中保留前15名。

答案 1 :(得分:0)

我在这里假设很多,但我们的想法是将您登录的用户表添加到查询中,并确保显示该表中记录的所有人。

SELECT TOP 15
a.MemberID,             -- 0
a.UserName,             -- 1
a.MemberDisplayName,    -- 2
a.NYKABizName           -- 3
FROM Member a
INNER JOIN AdDisplay b ON b.MemberID = a.MemberID
LEFT OUTER JOIN LoggedInUsers l ON a.MemberID = l.MemberID
WHERE (a.Claimed = 'Y'
AND a.NYKACatID IS NOT NULL
AND b.LocalPageID = @LocalPageID
AND a.SBIcon = 'N'
AND a.Viewable = 'Y'
AND a.ProfileTypeID <> 1
AND a.PackageType <> 'G'
AND a.PackageType <> 'P'
AND a.PackageType <> 'C')
OR l.MemberID IS NOT NULL
ORDER BY IF(l.MemberID IS NOT NULL,0,1), PackageType ASC

当然如果你总是想要静态地包含MemberID = 102,那么@ GordonLinoff的回答是正确的。也许我太在意你的问题。

答案 2 :(得分:0)

您可以编写第二个类似于第一个查询的查询,但只返回登录成员的结果,并且两个查询都包含一个额外的值来标识它们来自哪个子查询,然后将它们联合起来并从中进行选择在外部查询中对它们进行排序。

我知道这是一个连续的句子,所以让我看看我是否可以详细说明代码......

SELECT TOP 15 * FROM (
    SELECT
      0 as loginStatus,
      a.MemberID,             -- 0 
      a.UserName,             -- 1 
      a.MemberDisplayName,    -- 2 
      a.NYKABizName           -- 3 
    FROM Member a 
    INNER JOIN AdDisplay b 
    ON b.MemberID = a.MemberID 
    WHERE a.Claimed = 'Y' 
    AND a.NYKACatID IS NOT NULL 
    AND b.LocalPageID = @LocalPageID 
    AND a.SBIcon = 'N' 
    AND a.Viewable = 'Y' 
    AND a.ProfileTypeID <> 1 
    AND a.PackageType <> 'G' 
    AND a.PackageType <> 'P' 
    AND a.PackageType <> 'C' 
    AND a.MemberID IN (@memberIdList)

    UNION

    SELECT
      1 as loginStatus,
      a.MemberID,             -- 0 
      a.UserName,             -- 1 
      a.MemberDisplayName,    -- 2 
      a.NYKABizName           -- 3 
    FROM Member a 
    INNER JOIN AdDisplay b 
    ON b.MemberID = a.MemberID 
    WHERE a.Claimed = 'Y' 
    AND a.NYKACatID IS NOT NULL 
    AND b.LocalPageID = @LocalPageID 
    AND a.SBIcon = 'N' 
    AND a.Viewable = 'Y' 
    AND a.ProfileTypeID <> 1 
    AND a.PackageType <> 'G' 
    AND a.PackageType <> 'P' 
    AND a.PackageType <> 'C'
)
ORDER BY loginStatus