日期:2014-05-17  浏览次数:20541 次

sql获取group数量
现有表如下:
id      money      user_id  project_id
1 1000.00    1      1
2 1000.00    1      1
3 500.00    1      1

我现在要根据project_id来分组 ,并获得分组的组数的数量。
我现在的slq是:select count(*) from invest_log vl where vl.project_id = 1 group by user_id
得到的结果是3 ,不是我想要的结果 。 正确应该为1

sql该如何改?

------解决方案--------------------
select count(*) 
from (select distinct user_id,project_id from invest_log) as vl 
where vl.project_id = 1 group by user_id

------解决方案--------------------
----------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2013-09-20 09:43:07
-- Version:
--      Microsoft SQL Server 2014 (CTP1) - 11.0.9120.5 (X64) 
-- Jun 10 2013 20:09:10 
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([d] int,[money] numeric(6,2),[user_id] int,[project_id] int)
insert [huang]
select 1,1000.00,1,1 union all
select 2,1000.00,1,1 union all
select 3,500.00,1,1
--------------开始查询--------------------------

select COUNT(DISTINCT(project_id))
from [huang]

----------------结果----------------------------
/* 

-----------
1
*/

------解决方案--------------------
select * from(
select row_number()over(partition by project_id order by project_id)num,* from invest_log)a
where num=1

------解决方案--------------------

select count(user_id) as group_num from 
(select user_id from invest_log vl where vl.project_id = 1 group by user_id) t