日期:2014-05-16  浏览次数:20407 次

求一句SQL

      公司ID   个人ID  访问次数
ID    Com_id   Per_id  Count
1     11        0       50
2     11        111     1
3     11        222     1
4     22        0       60
5     22        333     1
6     22        444     1
7     22        555     1

访问公司的时候,如果个人登录了,插记录的时候per_id就存个人ID,未登录就在per_id那条的count+1
最后的统计报表需要:公司ID,个人访问总数,未登录的访问数    显示在一排。
求一SQL



------解决方案--------------------
select Com_id ,sum( case when per_id<>0 then count else 0 end)as Logcount,

sum( case when per_id=0 then count else 0 end)as NotLogCount
  from table 
group by Com_id   
------解决方案--------------------
----------------------------------------------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2014-01-22 13:22:43
-- Version:
--      Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64) 
-- Dec 28 2012 20:23:12 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([ID] int,[Com_id] int,[Per_id] int,[Count] int)
insert [huang]
select 1,11,0,50 union all
select 2,11,111,1 union all
select 3,11,222,1 union all
select 4,22,0,60 union all
select 5,22,333,1 union all
select 6,22,444,1 union all
select 7,22,555,1
--------------开始查询--------------------------
      
select com_id 公司ID,SUM([count]) 访问总数,SUM(CASE WHEN per_id=0 THEN [count] ELSE NULL END )游客总数
from [huang]
GROUP BY com_id
----------------结果----------------------------
/* 
公司ID        访问总数        游客总数
----------- ----------- -----------
11          52          50
22          63          60
*/