我有这样的查询(从myTable中选择id,reffid,someData):
id reffid someData 8 10 text1 9 10 text2 10 11 text3 11 11 text4 12 11 text5 13 11 text6 14 12 text7 15 12 text8 16 12 text9 17 13 text10 18 14 text11
我需要查询,它将执行以下操作:如果我有少于4个具有相同值的reffid,则添加具有相同reffid的行,并在someData中添加 - 。结果查询应如下所示:
id reffid someData 8 10 text1 9 10 text2 ??? 10 - ??? 10 - 10 11 text3 11 11 text4 12 11 text5 13 11 text6 14 12 text7 15 12 text8 16 12 text9 ??? 12 - 17 13 text10 ??? 13 - ??? 13 - ??? 13 - 18 14 text11 ??? 14 - ??? 14 - ??? 14 -
如何做到这一点?
答案 0 :(得分:1)
尝试
SELECT t.id, l.reffid, COALESCE(t.somedata, '-') someData
FROM
(
SELECT reffid, rnum
FROM
(
SELECT DISTINCT reffid
FROM table1
) q CROsS JOIN
(
SELECT 1 rnum UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4
) n
) l LEFT JOIN
(
SELECT id, reffid, somedata,
ROW_NUMBER() OVER (PARTITION BY reffid ORDER BY id) rnum
FROM table1
) t
ON l.reffid = t.reffid
AND l.rnum = t.rnum
输出:
| ID | REFFID | SOMEDATA | |--------|--------|----------| | 8 | 10 | text1 | | 9 | 10 | text2 | | (null) | 10 | - | | (null) | 10 | - | | 10 | 11 | text3 | | 11 | 11 | text4 | | 12 | 11 | text5 | | 13 | 11 | text6 | | 14 | 12 | text7 | | 15 | 12 | text8 | | 16 | 12 | text9 | | (null) | 12 | - | | 17 | 13 | text10 | | (null) | 13 | - | | (null) | 13 | - | | (null) | 13 | - | | 18 | 14 | text11 | | (null) | 14 | - | | (null) | 14 | - | | (null) | 14 | - |
这是 SQLFiddle 演示