用内连接计数

时间:2015-08-27 15:16:59

标签: sql

我一直在计算我的程序时遇到问题。

我的SQL查询是:

select table_3.SERIAL, TABLE_3.ID, Table_3.OPERATOR, TABLE_1.PROGRAM, TABLE_1.COLOR, tABLE_1.PART_customer 
from table_3 
inner join table_1
    on Table_1.[SERIAL]=table_3.[SERIAL]
GROUP BY TABLE_3.SERIAL,TABLE_3.ID,TABLE_3.OPERATOR,TABLE_1.PROGRAM,Table_1.COLOR,Table_1.PART_customer

我的输出是

Serial  id   operator   program       color     part_CUSTOMER   
104451  1       a1      GMT-172       Switch    23250063
104451  1       a1      GMT-177       Summit    23214845
104552  9       b1      GMT-172       Switch    23250063
104552  9       b1      GMT-177       Summit    23214845
104855  3       c1      GMT-172       Switch    23250063
104855  3       c1      GMT-177       Summit    23214845

我需要按照我应该获得的方式来计算它们

Serial  id   operator   program       color     part_CUSTOMER      TOTAL
104451  1       a1      GMT-172       Switch    23250063             2
104552  9       b1      GMT-172       Switch    23250063             2
104855  3       c1      GMT-172       Switch    23250063             2

1 个答案:

答案 0 :(得分:0)

您似乎不希望输出中出现programcolor。据我所知,你正在为他们选择任意值。

因此,只需按您需要的值汇总并添加计数:

select t3.SERIAL, t3.ID, t1.operator, t1.PART_customer, COUNT(*)
from table_3 t3 inner join
     table_1 t1
     on t1.[SERIAL] = t3.[SERIAL]
group by t3.SERIAL, t3.ID, t1.operator, t1.PART_customer;

如果您想要programcolor值,则可以根据需要使用MIN()MAX()

编辑:

从技术上讲,你可以通过以下方式获得你想要的东西:

select t.*
from (select t3.SERIAL, t3.ID, t1.operator, t1.PROGRAM, t1.COLOR, t1.PART_customer,
             COUNT(*) OVER (PARTITOIN BY t3.SERIAL, t3.ID, t1.operator, t1.PART_customer) as cnt
      from table_3 t3 inner join
           table_1 t1
           on t1.[SERIAL] = t3.[SERIAL]
     ) t
where program = 'GMT-172';