1

I would like to know the query where I can get the normal set of columns and add a column that contains the number of records in database..

For example, let's say I have these data..

ColA   ColB   ColC
----   ----   ----
1AB1   CARR   APPL
2BC1   APPL   APPL
1AB1   MAXR   APPL

from those lines, I would like to generate these columns

ColA   ColB   ColC   Count
----   ----   ----   -----
1AB1   CARR   APPL     2

A. This is my current select statement so far..

SELECT top 1 myTBL.* from mydb WHERE ColA = '1AB1'

B. But i couldn't seem to add the following code to get my fourth column..

SELECT count(myTBL.*) as Count from mydb WHERE ColA = '1AB1'

P.S. I would like to get a select statement that combines A and B select statements that I have. The error I'm getting says something about GROUP BY clause.. I'm having a hard time to understand this.. I hope you could formulate the correct select statement I can use for the given example.. Thanks for all the help..

4

4 回答 4

3

有几种方法可以做到这一点,但是,如果没有明显的主键,分析函数(也称为窗口函数)看起来是一个不错的选择。

select cola, colb, colc, cnt as "Count" from (
select
cola,
colb,
colc,
row_number () over (partition by cola order by colb) rn,
count (*) over (partition by cola) cnt

from
table1

where cola = '1AB1'
) as d
where rn = 1 

这给出了:

+------------+------------+------------+-------+
|    cola    |    colb    |    colc    | Count |
+------------+------------+------------+-------+
| 1AB1       | CARR       | APPL       |     2 |
+------------+------------+------------+-------+
于 2012-12-21T08:57:48.017 回答
1
SELECT TOP 1 ColA, ColB, ColC, COUNT(*) OVER (PARTITION BY ColA) AS Count
FROM mydb
WHERE ColA = '1AB1'

SQLFiddle上的演示

于 2012-12-25T16:06:59.593 回答
0

如果你只想要 ColA 的数量,我会做这样的事情

SELECT top 1 cola,colb,colc, (SELECT count(*) from mytbl t2 WHERE t2.ColA = t1.colA) 
FROM mytbl t1 
WHERE cola = '1AB1'

当您使用子查询时,您不能使用 mytbl.*

另一种方式是:

Select t1.*,t2.count 
FROM mytbl t1 ,
(SELECT cola,count(*) as "count" from mytbl t2 group by cola) t2
where t1.cola = t2.cola
于 2012-12-21T08:54:52.037 回答
0

下面的查询将对 COLA 上表中的值进行分组和计数,并通过计数链接回 ColA 上的原始表。

SELECT myTable.ColA , myTable.ColB, myTable.ColC, ColASummary.ColA_Count 
FROM myTable
INNER JOIN 
(
SELECT ColA, COUNT(ColA) AS ColA_Count 
FROM myTable 
GROUP By ColA
)  AS ColASummary
ON myTable.ColA = ColASummary.ColA

如果其他列也需要相同的内容,则可以以这种方式链接其他汇总表。

于 2012-12-21T10:49:44.960 回答