我有表sales
存储每天的交易。
Date Receipt Total
4/21/2018 325 600
4/21/2018 326 800
4/21/2018 327 500
4/21/2018 328 900
4/21/2018 329 500
4/26/2018 330 600
4/26/2018 331 1080
4/26/2018 332 1200
4/26/2018 333 1120
4/29/2018 334 600
4/29/2018 335 1400
5/1/2018 336 1500
5/1/2018 337 4000
5/1/2018 338 6000
从上表中,我需要为每天选择前30%的条目,表格应如下所示。
Date Receipt Total
4/21/2018 325 600
4/21/2018 326 800
4/26/2018 330 600
4/26/2018 331 1080
4/29/2018 334 600
5/1/2018 336 1500
5/1/2018 337 4000
我使用了以下代码:
SELECT TOP 30 percent *
FROM sales
GROUP BY Date
答案 0 :(得分:1)
您可以将row_number()
与partition by date
一起使用,并检查每天总数的30%。
select date,receipt,total
from (select *,
ceiling(tc * 30.00 / 100.00) as under30
from (select date,
receipt,
total,
row_number() over(partition by date order by (select null)) rn,
count(*) over(partition by date order by (select null)) tc
from sales) t
) t1
where rn <= under30
<强> DEMO 强>
<强>输出:强>
+------------+---------+-------+
| date | receipt | total |
+------------+---------+-------+
| 2018-04-21 | 325 | 600 |
+------------+---------+-------+
| 2018-04-21 | 326 | 800 |
+------------+---------+-------+
| 2018-04-26 | 330 | 600 |
+------------+---------+-------+
| 2018-04-26 | 331 | 1080 |
+------------+---------+-------+
| 2018-04-29 | 334 | 600 |
+------------+---------+-------+
| 2018-05-01 | 336 | 1500 |
+------------+---------+-------+
注意:如果您想要总数的30%,则需要在上述查询中更改计数计算逻辑。
count(*) over(order by (select null)) tc