SQL 临时将计数列添加到返回的结果集中
Posted
技术标签:
【中文标题】SQL 临时将计数列添加到返回的结果集中【英文标题】:SQL Temporary Added Count column to a returned set of results 【发布时间】:2011-08-02 18:52:53 【问题描述】:我有以下代码将两个不同的表连接在一起并提供我需要的离散数据列。问题是我还需要一个列来计算另一个表中的另一个实例。请参阅 select 语句下方的指针引用。
SELECT
//count(of records returned from below query and duplicates of those found in outc table),
outage_duration.dgroup,
outage_duration.cause,
outage_duration.cdts,
outage_duration.cust_minutes,
outage_duration.evntnum,
outage_duration.num_cust,
outage_duration.outage_type,
outage_duration.substation,
outage_duration.feeder,
outage_duration.out_minutes
FROM outage_duration,
aeven
WHERE outage_duration.evntnum = aeven.num_1
AND aeven.outage_type = 'T'
AND aeven.cdts >= '20110101060000UT'
AND aeven.curent = 'T'
AND aeven.open_and_curent = 'F'
AND aeven.ag_id NOT IN ('MEMT','MTRRDR','MTRTECH','GRDLT','FSRSR','ELECOPS','AMS','REVSEC')
AND outage_duration.out_minutes >= '240'
AND outage_duration.curent = 'T'
GROUP BY outage_duration.dgroup, outage_duration.cause, outage_duration.cdts, outage_duration.cust_minutes, outage_duration.evntnum, outage_duration.num_cust, outage_duration.outage_type, outage_duration.substation, outage_duration.feeder, outage_duration.out_minutes
ORDER BY outage_duration.evntnum
AEVEN 示例,Outage_Duration 表
num_1
T344490
T344410
T344480
outage_duration
T344490
T344410
这将返回 T344490 和 T44410,这就是上述搜索所做的。现在有了这些结果,我需要从另一个表中完全计数,并将计数显示为它自己的列,旁边是该表中有多少次发生的事件编号。
outc(第 1 列 = 唯一 ID,第 2 列 = evntnum)
1. 1, T344490
2. 2, T344490
3. 3, T344410
4. 5, T344410
5. 6, T344410
6. 7, T344410
7. 8, T344410
期望的结果如下:
1. T344410, 5, "other columns that were specified"
2. T344490, 2, "other columns that were specified"
我将如何做到这一点?
【问题讨论】:
从 sqldeveloper 自动添加,当我复制粘贴时。 【参考方案1】:SELECT
COUNT(*), --this
outage_duration.dgroup,
outage_duration.cause,
outage_duration.cdts,
outage_duration.cust_minutes,
outage_duration.evntnum,
outage_duration.num_cust,
outage_duration.outage_type,
outage_duration.substation,
outage_duration.feeder,
outage_duration.out_minutes
FROM
outage_duration
JOIN
aeven ON outage_duration.evntnum = aeven.num_1
JOIN
outc ON outage_duration.evntnum = outc. --insert column here
WHERE
AND aeven.outage_type = 'T'
AND aeven.cdts >= '20110101060000UT'
AND aeven.curent = 'T'
AND aeven.open_and_curent = 'F'
AND aeven.ag_id NOT IN ('MEMT','MTRRDR','MTRTECH','GRDLT','FSRSR','ELECOPS','AMS','REVSEC')
AND outage_duration.out_minutes >= '240'
AND outage_duration.curent = 'T'
GROUP BY outage_duration.dgroup, outage_duration.cause, outage_duration.cdts, outage_duration.cust_minutes, outage_duration.evntnum, outage_duration.num_cust, outage_duration.outage_type, outage_duration.substation, outage_duration.feeder, outage_duration.out_minutes
ORDER BY outage_duration.evntnum
只需将 COUNT(*) 添加到 SELECT 位,并将表输出添加到 FROM
你已经有一个 GROUP BY 所以应该把它插入它n
【讨论】:
以上是关于SQL 临时将计数列添加到返回的结果集中的主要内容,如果未能解决你的问题,请参考以下文章