如何表达2阶段循环T-SQL SELECT查询?

时间:2012-04-26 14:55:53

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

这是SQL专家的问题!

我正在使用SQL SERVER 2008 R2 Express。

我有一个名为[myTable]的表,包含两种类型的记录。

第一类记录是主记录,第二类记录是[Relative]记录。

每条主记录可能有几条相关记录。

我想SLELECT TOP 10 * FROM [myTable]主记录,以及每个SELECT TOP 4 [Relative]个记录的联合子记录。

每条记录都有[PKID] NO NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED列。

我想我需要这样的东西:

SELECT TOP 10 * FROM [myTable]  WHERE [Relative]=0 
UNION
For each (SELECT TOP 10 [PKID] as Master, * FROM [myTable] WHERE [Relative]=0 )
{SELECT TOP 4 * FROM [myTable] WHERE [Relative] = Master}

如何更正查询以实现目标?

我有一个次要问题,我怀疑它有一个简单的解决方案:

相对记录有两种风格,如[IsImportant]列所述。

有没有办法确保每个主记录只选择一条重要的相对记录?

如果有少于4条相对记录,有没有办法跳过主记录,而只有其中只有1条是重要的?

1 个答案:

答案 0 :(得分:5)

修改

这是对你的要求的正确解释吗?

[myTable]有3个相关领域......

  • PKID:每行的唯一标识符
  • relative:行父项的PKID(如果行没有父项,则为0 [AKA - 主站])
  • IsImportant:0/1 flag

    1. 返回不超过10条主记录
    2. 对于每个主记录,返回不超过4个相对记录
    3. 在4个相对记录中,返回不超过1个IsImportant记录
    4. 跳过任何少于4个亲戚的主人(将所有IsImportant视为1)

问题:
  - 如果一个主人有3个相对记录,而且没有一个是重要的,那么仍然会跳过?   - 如果一个主人有4个相对记录,并且多于1是重要的,还是跳过?

最佳猜测答案......

WITH
  master_metadata
AS
(
  SELECT
    relative         AS MasterID,
    COUNT(*)         AS Relatives,
    SUM(isImportant) AS IsImportantRelatives
  FROM
    [myTable]
  WHERE
    relative <> 0
  GROUP BY
    relative
  HAVING
    COUNT(*) - SUM(isImportant) + MAX(isImportant) >= 4
)
,
  master
AS
(
  SELECT TOP 10
    NULL AS sequence_id,
    [myTable].*,
    [master_metadata].Relatives,
    [master_metadata].IsImportantRelatives
  FROM
    [myTable]
  INNER JOIN
    [master_metadata]
      ON [master_metadata].MasterID = [myTable].PKID
  ORDER BY
    [myTable].Selector
)
,
  relative
AS
(
  SELECT
    ROW_NUMBER() OVER (PARTITION BY relative, IsImportant ORDER BY Selector)  AS sequence_id,
    *
  FROM
    [myTable]
)
,
  data
AS
(
  SELECT
    PKID AS MasterID,
    *
  FROM
    [master]

  UNION ALL

  SELECT
    [master].PKID AS MasterID,
    [relative].*, Relatives, IsImportantRelatives
  FROM
    [master]
  INNER JOIN
    [relative]
      ON  ([relative].relative = [master].PKID)
      AND (  ([relative].isImportant = 1 AND [relative].sequence_id  = 1)
          OR ([relative].isImportant = 0 AND [relative].sequence_id <= 3)
          OR ([relative].isImportant = 0 AND [relative].sequence_id  = 4 AND [master].IsImportantRelatives = 0)
          )
)

SELECT
  *
FROM
  [data]
ORDER BY
  MasterID,
  CASE WHEN MasterID = PKID THEN 0 ELSE 1 END,
  IsImportant DESC,
  relative