1

这是一个 SQL 专家的问题!

我正在使用 SQL SERVER 2008 R2 Express。

我有一个名为[myTable]由 2 种类型的记录组成的表。

第一种记录是主记录,第二种是[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 个很重要,是否有办法跳过主记录?

4

1 回答 1

5

编辑

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

[myTable] 有 3 个相关字段...

  • PKID :每行的唯一标识符
  • relative : 行父级的 PKID(如果行没有父级 [AKA - a master],则为 0)
  • IsImportant : 0/1 标志

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

问题:
- 如果一个master有3个相关记录,并且没有一个是isImportant,还跳过吗?
- 如果一个master有4条相关记录,并且超过1条是isImportant,还跳过吗?

最佳猜测答案...

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
于 2012-04-26T15:03:14.023 回答