如何在一列中对数据进行分组?
Posted
技术标签:
【中文标题】如何在一列中对数据进行分组?【英文标题】:How to group data inside one column? 【发布时间】:2014-02-17 03:31:50 【问题描述】:我是 Oracle SQL 的新手。我试图显示票的名称、关闭和打开票的数量以及日期。但我无法得到正确的查询。
期望的输出:
01/20/2014, User management, 20, 15
查询:
SELECT 'Data'
||','||TO_CHAR(D.DTIME_DAY,'MM/dd/yyyy')
||','||q.name -- as ticket
||','||NVL(o.CNT_OPENED,0) --as cnt_opened
||','||NVL(c.CNT_CLOSED,0) --as cnt_closed
FROM OWNER_DWH.DC_DATE d
LEFT JOIN (
SELECT q.name, count(q.name), TRUNC(t.CREATE_TIME) as report_date, count(*) as cnt_opened
FROM APP_ACCOUNT.OTRS_TICKET t
left join app_account.otrs_queue q
ON q.ID = t.QUEUE_ID
WHERE t.CREATE_TIME BETWEEN SYSDATE -7 AND SYSDATE -1
and t.queue_id not in (63, 61, 69, 59, 58, 60, 56, 64, 65, 23, 67, 68, 57)
GROUP BY q.name, TRUNC(t.CREATE_TIME)
) o ON d.DTIME_DAY=o.REPORT_DATE
LEFT JOIN (
SELECT q.name, count(q.name), TRUNC(t.CLOSE_TIME) as report_date,count(*) AS cnt_closed
FROM APP_ACCOUNT.OTRS_TICKET t
left join app_account.otrs_queue q
ON q.ID = t.QUEUE_ID
WHERE t.CLOSE_TIME BETWEEN SYSDATE -7 AND SYSDATE -1
and t.queue_id not in (63, 61, 69, 59, 58, 60, 56, 64, 65, 23, 67, 68, 57)
GROUP BY q.name, TRUNC(t.CLOSE_TIME)
) c ON D.DTIME_DAY=c.REPORT_DATE
WHERE d.DTIME_DAY BETWEEN SYSDATE -7 AND TRUNC(SYSDATE) -1
AND TRUNC(d.DTIME_DAY)= d.DTIME_DAY
ORDER BY D.DTIME_DAY;
如果我想对数据进行分组?
示例:在一列中,假设我有:
E-mail management
E-mail management::Add user e-mail
E-mail management::Add new Outlook distribution list
E-mail management::Add new Outlook shared mailbox
E-mail management::Add new SA e-mail (Zimbra account)
POS::POS issue - need paper
POS::POS issue - internet connection problems
所有有E-mail管理的名字都归为E-mail管理,所有有POS的名字都归为POS。
希望输出:
02/10/2014, E-mail, 4
02/10/2014, POS, 2
怎么做?
请帮助我。提前谢谢你。
【问题讨论】:
【参考方案1】:你可以这样做:
group by (case when col like 'E-mail management:%' then 'E-mail management'
when col like 'pos:%' then 'pos'
else col
end)
按冒号前的部分聚合:
group by substr(col, 1, instr(col, ':') - 1)
或
group by (case when col like '%:%' then substr(col, 1, instr(col, ':') - 1)
else col
end)
当然,您必须修复 select
子句以与 group by
子句兼容。
编辑:
要计算组中的数字,您可以执行以下操作:
select (case when col like '%:%' then substr(col, 1, instr(col, ':') - 1)
else col
end), count(*)
from table t
group by (case when col like '%:%' then substr(col, 1, instr(col, ':') - 1)
else col
end)
【讨论】:
如何显示日期本身? 你必须使用聚合函数,例如min()
或list_agg()
。以上是关于如何在一列中对数据进行分组?的主要内容,如果未能解决你的问题,请参考以下文章