时间:2017-11-14 16:29:04

标签: sql oracle group-by distinct

我需要帮助:我有这张桌子:

DAY     WO
 1     1000
 1     1009
 1     2056
 2     1003
 2     1006
 2     1000
 3     1009
 3     6787
 4     7000
 4     7020

我需要按天划分不同的WO,但不仅在我分组的那一天,在前几天也是如此,以获得这个:

DAY    WO
 1      3 (1000,1009,2056)
 2      2 (1003,1006)
 3      1 (6787)
 4      2 (7000,7020)

感谢您的帮助

Sample 2:
DAY   WO
6   379157
9   379157
10  379404
10  379362
19  386118
24  386547
25  388711
25  386547
30  386547

4 个答案:

答案 0 :(得分:2)

您可以使用以下查询:

SELECT DAY, COUNT(DISTINCT WO)
FROM (
   SELECT MIN(DAY) AS DAY, WO
   FROM mytable 
   GROUP BY WO) AS t
GROUP BY DAY    

Demo here

说明:内部查询提供与每个Day值相关的第一个 WO(如果首先表示最小值{{1}然后,外部查询可以执行Day操作,以获得每COUNT DISTINCT个不同WO值的数量。

修改:要返回所有天,即使没有 DAY,也可以使用以下查询:< / p>

WO

Demo here

答案 1 :(得分:0)

您希望使用LISTAGG将值连接在一起,并为格式化添加一些额外的字符串连接:

-- START: table data mockup
with days as
(
    select 1 as "day", 1000 as "wo" from dual
    union all
    select 1 as "day", 1009 as "wo" from dual
    union all
    select 1 as "day", 2056 as "wo" from dual
    union all
    select 2 as "day", 1003 as "wo" from dual
    union all
    select 2 as "day", 1006 as "wo" from dual
    union all
    select 2 as "day", 1000 as "wo" from dual
    union all
    select 3 as "day", 1009 as "wo" from dual
    union all
    select 3 as "day", 6787 as "wo" from dual
    union all
    select 4 as "day", 7000 as "wo" from dual
    union all
    select 4 as "day", 7020 as "wo" from dual
)
-- END: table data mockup

select "day", count("wo") || ' (' || listagg("wo", ',') within group (order by "wo") || ')' "WO"
from days d1
where d1."wo" not in
(
    select d2."wo"
    from days d2
    where d2."day" < d1."day"
)
group by "day";

答案 2 :(得分:0)

select a.day_number, count(a.WO) as WO_count
from (
SELECT * FROM data d 
WHERE d.day_number = ( 
SELECT MIN(day_number) FROM data d2
WHERE d.WO = d2.WO

) 
) as a
group by a.day_number

答案 3 :(得分:0)

使用row_number枚举工单发生次数,然后过滤掉除每个工作单的第一行以外的所有行,并计算剩下的内容。

SELECT day, count(*) wo
FROM (SELECT day, row_number() OVER (PARTITION BY wo ORDER BY day) rn
      FROM day_wo) t
WHERE rn = 1
GROUP BY day
ORDER BY day;