当前位置: 代码迷 >> Sql Server >> SQL 2008 R2 查询统计,该怎么解决
  详细解决方案

SQL 2008 R2 查询统计,该怎么解决

热度:35   发布时间:2016-04-24 10:28:26.0
SQL 2008 R2 查询统计
本帖最后由 u011062542 于 2014-06-27 17:29:22 编辑
有如下一个表:

查询规则:
1、根据station_id和ng_code统计数据
2、test_count字段为该station_id的测试总数
3、ng_count字段为该station_id且为该ng_code的数量
想要的效果如下:
prduct    station_id    test_count    ng_count    ng_code
P_001    S_001         6                     2                   N_001
P_001    S_001         6                     1                   N_002
P_001    S_002         4                     2                   N_001
P_001    S_002         4                     1                   N_002
P_001    S_002         4                     1                   N_003

TableName: [statistics_table]
万分感谢!
------解决方案--------------------
两个子查询求和,分别group by prduct  station_id ng_code和prduct  station_id,两个子查询做联结,条件是prduct  station_id
------解决方案--------------------
select
    [product], [station_id],
    count()over(partition by station_id) as  test_count    ,
    count(1) as ng_count ,ng_code
from
    [statistics_table] 
group by
    [product],[station_id],[ng_code]
    

--TRY
------解决方案--------------------
本帖最后由 ap0405140 于 2014-06-27 22:04:40 编辑
try this,

select a.product,a.station_id,a.test_count,
       b.ng_count,b.ng_code
 from
(select product,
        station_id,
        count(1) 'test_count'
 from [表名]
 group by product,station_id) a
inner join
(select product,station_id,ng_code,count(1) 'ng_count'
 from [表名]
 where result='FALSE'
 group by product,station_id,ng_code) b 
on a.product=b.product and a.station_id=b.station_id
  相关解决方案