对两列SQL进行采样

时间:2017-06-27 13:18:49

标签: sql sql-server reporting-services reportbuilder3.0

我在一家进行物业维修的公司工作。每个修理都有一个唯一的编号,每个属性(大约15000条记录)和每个工人(大约有30个)都有。每个月我们都会进行2000到4000次维修。

为了让公司进行满意度调查,我们需要随机(最好,但可以只使用TOP)每个工人每月选择5个房产,同时确保房产以前没有在之前的3个房产内进行调查月(这将是一个属性)。

基本上我正在寻找一个提示来执行以下操作:

+-------+---------+-------+-----------------+ | Place | Worker | Date | previous survey | +-------+---------+-------+-----------------+ | 0001 | 1 | june1 | | | 0002 | 1 | june1 | | | 0003 | 2 | june1 | | | 0004 | 1 | june1 | Y | | 0005 | 2 | june1 | | | 0006 | 2 | june1 | | | 0007 | 1 | june1 | | | 0008 | 1 | june1 | | | 0009 | 1 | june1 | | | 0010 | 2 | june1 | | | 0011 | 1 | june1 | | | 0012 | 2 | june1 | | | 0013 | 1 | june1 | | | 0014 | 1 | june1 | Y | | 0015 | 1 | june1 | | +-------+---------+-------+-----------------+

对外输出:

Worker | Place 1 |0001 1 |0002 1 |0007 1 |0008 1 |0009 2 |0003 2 |0005 2 |0006 2 |0012 2 |NULL ....等等。

任何帮助都会非常感激,我甚至不知道谷歌要开始对此进行排序!

2 个答案:

答案 0 :(得分:3)

您可以轻松利用ROW_NUMBER进行此类操作。

https://docs.microsoft.com/en-us/sql/t-sql/functions/row-number-transact-sql

with SortedResults as
(
    select *
        , ROW_NUMBER() over (partition by Worker order by (Select newid())) as RowNum
    from YourTable
    where PreviousSurvey is null --or whatever the predicate would be here
)

select *
from SortedResults
where RowNum <= 5

答案 1 :(得分:0)

SELECT worker_id, place 
FROM <yourtable> 
WHERE previous_survey != 'Y' 
ORDER BY place ASC LIMIT 5