这是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条是重要的?
答案 0 :(得分:5)
修改强>
这是对你的要求的正确解释吗?
[myTable]有3个相关领域......
IsImportant:0/1 flag
问题:
- 如果一个主人有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