我正在尝试总结看起来像这样的T-SQL输出:
+---------+---------+-----+-------+
| perf_no | section | row | seat |
+---------+---------+-----+-------+
| 7128 | 6 | A | 4 |
| 7128 | 6 | A | 5 |
| 7128 | 6 | A | 7 |
| 7128 | 6 | A | 9 |
| 7128 | 6 | A | 28 |
| 7129 | 6 | A | 29 |
| 7129 | 6 | A | 8 |
| 7129 | 6 | A | 9 |
| 7129 | 8 | A | 6 |
| 7129 | 8 | B | 3 |
| 7129 | 8 | B | 4 |
+---------+---------+-----+-------+
将一行与下面的行进行比较,如果perf_no,section和row值相同,并且席位值之间的差为1,那么我想将它们视为一组并计算数量该组中的行数。
为您提供一个真实的例子,这些是剧院中的座位!我正在尝试总结可用的座位。
使用上表说明:
因此上表的输出看起来有点像...
(我留在了空格处,以便视觉上可以更轻松地看到分组-显然最终版本将没有分组)
+---------+---------+----------+-------+
| perf_no | section | seat_row | total |
+---------+---------+----------+-------+
| 7128 | 6 | A | 2 |
| | | | |
| 7128 | 6 | A | 1 |
| 7128 | 6 | A | 1 |
| 7128 | 6 | A | 1 |
| 7129 | 6 | A | 1 |
| 7129 | 6 | A | 2 |
| | | | |
| 7129 | 6 | A | 1 |
| 7129 | 8 | B | 2 |
+---------+---------+----------+-------+
我一直在尝试使用一些条件案例语句,但没有多大用处。非常感谢收到任何帮助!
答案 0 :(得分:2)
这是一种空白和岛屿问题。您可以通过从row_number()
中减去序列(由seat
生成)来生成分组:
select perf_no, section, row, count(*) as num_seats,
min(seat) as first_seat, max(seat) as last_seat
from (select t.*,
row_number() over (partition by perf_no, section, row order by seat) as seqnum
from t
) t
group by perf_no, section, row, (seat - seqnum);