在向SQL表添加虚拟填充行时,我需要帮助。该表包含带有familyID的家庭卡,但我需要为非家庭的家庭添加填充符
下面是一个示例。我本质上是想添加保留familyID的填充行,以确保每个家族都是4的倍数。
如果这个家庭有3个人,我将添加1个填充物 4人无所事事 5 ppl加3填料 1 ppl加3种填充剂等。
+----------+-----------+----------+
| FamilyID | FirstName | LastName |
+----------+-----------+----------+
| 1234 | Janet | Roberts |
+----------+-----------+----------+
| 1234 | Kevin | Roberts |
+----------+-----------+----------+
| 1234 | DUMMY | DUMMY |
+----------+-----------+----------+
| 1234 | DUMMY | DUMMY |
+----------+-----------+----------+
| 3423 | Adam | Lake |
+----------+-----------+----------+
| 3423 | DUMMY | DUMMY |
+----------+-----------+----------+
| 3423 | DUMMY | DUMMY |
+----------+-----------+----------+
| 3423 | DUMMY | DUMMY |
+----------+-----------+----------+
| 1111 | April | Lo |
+----------+-----------+----------+
| 1111 | Randy | Lo |
+----------+-----------+----------+
| 1111 | Abby | Lo |
+----------+-----------+----------+
| 1111 | Ray | Lo |
+----------+-----------+----------+
| 1111 | Sandra | Lo |
+----------+-----------+----------+
| 1111 | DUMMY | DUMMY |
+----------+-----------+----------+
| 1111 | DUMMY | DUMMY |
+----------+-----------+----------+
| 1111 | DUMMY | DUMMY |
+----------+-----------+----------+
答案 0 :(得分:1)
我明白了。我不确定您要查询select
还是insert
。以下生成额外的行:
select familyid, 'DUMMY', 'DUMMY'
from (select familyid, count(*) as cnt
from t
group by familyid
) t join
(values (1), (2), (3)) as n(n)
on (cnt % 4) <= 4 - n.n
where cnt % 4 > 0;
对于select
,您可以使用union all
:
insert into t(FamilyId, FirstName, LastName)
select familyid, 'DUMMY', 'DUMMY'
from (select familyid, count(*) as cnt
from t
group by familyid
) t join
(values (1), (2), (3)) as n(n)
on (cnt % 4) <= 4 - n.n
where cnt % 4 > 0;