Reputation: 1813
Here is what i am trying to get:-
SELECT
Column1,
Count(Column1),
Count(Column2)
FROM Table1
I know this query is invalid. But is there any way I can all the values of Column1 and Count of Column1 and Count of Column2.
Upvotes: 0
Views: 652
Reputation: 432210
The OVER clause modifies the aggregate range to allow the query to happen as you want
SELECT
Column1,
Count(Column1) OVER (),
Count(Column2) OVER ()
FROM Table1
Edit:
above for SQL Server 2005+
Edit 2:
The CROSS JOIN/COUNT solution in SQL Server 2000 is not reliable under load.
Try this from multiple connections, note @@ROWCOUNT never equals T2.cnt in connection 2
--connection 1
set nocount on;
drop table dbo.test_table;
GO
create table dbo.test_table
(
id_field uniqueidentifier not null default(newid()),
filler char(2000) not null default('a')
);
GO
create unique clustered index idx_id_fld on dbo.test_table(id_field);
GO
while 1 = 1
insert into dbo.test_table default values;
--connection 2
select T2.cnt, T1.id_field, T1.filler
from dbo.test_table T1
cross join (select COUNT(*) as cnt from dbo.test_table) T2
SELECT @@ROWCOUNT
select T2.cnt, T1.id_field, T1.filler
from dbo.test_table T1
cross join (select COUNT(*) as cnt from dbo.test_table) T2
SELECT @@ROWCOUNT
select T2.cnt, T1.id_field, T1.filler
from dbo.test_table T1
cross join (select COUNT(*) as cnt from dbo.test_table) T2
SELECT @@ROWCOUNT
Edit3: cyberkiwi stated the test is wrong. Rubbish.
If you forget @@ROWCOUNT, you can see cnt
is different to the row count in SSMS "grid mode"
Now, you use SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
and it does give correct results, but if you are busy enough to get inconsistent results do you really want to run this?
Use a temp table to ensure a consistent dataset if you are running SQL Server 2000.
Upvotes: 1
Reputation: 4827
The question, as asked, does not make sense. Do you mean that you want the counts of individual combinations of values of Col1 and Col2? If so:
select column1,column2,count(*)
from table1
group by column1, column2
If this is not what you want please try to give some sample data, what the inputs might look like and what your desired output would be.
Upvotes: 0
Reputation: 494
Try:
SELECT column1,(SELECT COUNT(Column1),COUNT(Column2)) AS CNT FROM Table1
That should get you what you want, then when you run your fetch command you use it like you would normally.
E.g. in php,
$rows = mysql_fetch_assoc(mysql_query($query));
echo $rows['CNT'];
Upvotes: 0