我想知道如何每6个月重置行级别号码。我总是希望保留第一个约会记录。然后计算6个月以获得我想要的下一个记录。我之间的任何记录都不需要。从第二个记录开始,计算6个月以上获得第三个记录。该过程只是循环,直到没有合格的记录。
以下是SQL和数据。
SQL
SELECT ID, DATE FROM MyTable ORDER BY ID, DATE
结果如下,
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
<h2>Table esult</h2>
<table style="width:40%">
<tr>
<th>ID</th>
<th>DATE</th>
</tr>
<tr>
<td>123</td>
<td>4/28/2016</td>
</tr>
<tr>
<td>123</td>
<td>5/27/2016</td>
</tr>
<tr>
<td>123</td>
<td>6/27/2016</td>
</tr>
<tr>
<td>123</td>
<td>7/21/2016</td>
</tr>
<tr>
<td>123</td>
<td>8/18/2016</td>
</tr>
<tr>
<td>123</td>
<td>9/22/2016</td>
</tr>
<tr>
<td>123</td>
<td>10/14/2016</td>
</tr>
<tr>
<td>123</td>
<td>11/18/2016</td>
</tr>
<tr>
<td>123</td>
<td>12/16/2016</td>
</tr>
<tr>
<td>123</td>
<td>1/20/2017</td>
</tr>
<tr>
<td>123</td>
<td>2/24/2017</td>
</tr>
<tr>
<td>123</td>
<td>3/24/2017</td>
</tr>
<tr>
<td>123</td>
<td>5/5/2017</td>
</tr>
<tr>
<td>123</td>
<td>6/26/2017</td>
</tr>
<tr>
<td>123</td>
<td>6/26/2017</td>
</tr>
<tr>
<td>123</td>
<td>6/27/2017</td>
</tr>
<tr>
<td>123</td>
<td>8/11/2017</td>
</tr>
<tr>
<td>123</td>
<td>9/8/2017</td>
</tr>
<tr>
<td>123</td>
<td>10/6/2017</td>
</tr>
<tr>
<td>123</td>
<td>10/6/2017</td>
</tr>
</table>
我想要达到的结果如下,
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
.highl {
background-color: coral
}
<h2>Table esult</h2>
<table style="width:40%">
<tr>
<th>ID</th>
<th>DATE</th>
<th>RANK</th>
</tr>
<tr class="highl">
<td>123</td>
<td>4/28/2016</td>
<td>1</td>
</tr>
<tr>
<td>123</td>
<td>5/27/2016</td>
<td>2</td>
</tr>
<tr>
<td>123</td>
<td>6/27/2016</td>
<td>3</td>
</tr>
<tr>
<td>123</td>
<td>7/21/2016</td>
<td>4</td>
</tr>
<tr>
<td>123</td>
<td>8/18/2016</td>
<td>5</td>
</tr>
<tr>
<td>123</td>
<td>9/22/2016</td>
<td>6</td>
</tr>
<tr>
<td>123</td>
<td>10/14/2016</td>
<td>7</td>
</tr>
<tr class="highl">
<td>123</td>
<td>11/18/2016</td>
<td>1</td>
</tr>
<tr>
<td>123</td>
<td>12/16/2016</td>
<td>2</td>
</tr>
<tr>
<td>123</td>
<td>1/20/2017</td>
<td>3</td>
</tr>
<tr>
<td>123</td>
<td>2/24/2017</td>
<td>4</td>
</tr>
<tr>
<td>123</td>
<td>3/24/2017</td>
<td>5</td>
</tr>
<tr>
<td>123</td>
<td>5/5/2017</td>
<td>6</td>
</tr>
<tr class="highl">
<td>123</td>
<td>6/26/2017</td>
<td>1</td>
</tr>
<tr>
<td>123</td>
<td>6/26/2017</td>
<td>2</td>
</tr>
<tr>
<td>123</td>
<td>6/27/2017</td>
<td>3</td>
</tr>
<tr>
<td>123</td>
<td>8/11/2017</td>
<td>4</td>
</tr>
<tr>
<td>123</td>
<td>9/8/2017</td>
<td>5</td>
</tr>
<tr>
<td>123</td>
<td>10/6/2017</td>
<td>6</td>
</tr>
<tr>
<td>123</td>
<td>10/6/2017</td>
<td>7</td>
</tr>
</table>
感谢任何帮助。谢谢。
答案 0 :(得分:0)
只需使用row_number()
:
SELECT ID, DATE,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DATE) as rank
FROM MyTable
ORDER BY ID, DATE;
如果您想在每个时间段重置此信息,请在PARTITION BY
中包含该信息:
SELECT ID, DATE,
ROW_NUMBER() OVER (PARTITION BY ID,
EXTRACT(YEAR FROM Date),
(CASE WHEN EXTRACT(MONTH FROM Date) IN (1, 2, 3, 4, 5, 6) THEN 1 ELSE 2 END)
ORDER BY DATE
) as rank
FROM MyTable
ORDER BY ID, DATE;