DB2 SQL COUNT() result from first table

99封情书 提交于 2020-01-25 06:49:30

问题


I posted something earlier and did not explain properly what I am trying to accomplish. I am trying a second time.

I want to return field value from two different table but want the count for only of the table. In this case the @SOP table. Right now it gives me total count of the @SOPREV table.

SELECT A.SOPSEQ, A.SOPNBR, B.REVUSR2 , COUNT(A.SOPSEQ) OVER() AS AAA
  FROM @SOP A
  INNER JOIN @SOPREV B on B.SOPSEQ = A.SOPSEQ
  WHERE UPPER(A.SOPSTS) = 'IN REVIEW' AND UPPER(B.REVSTS) = 'IN REVIEW'
  GROUP BY A.SOPSEQ, A.SOPNBR, B.REVUSR2
  ORDER BY A.SOPNBR, A.SOPREV

  OFFSET (:StartingRow - 1) * :NbrOfRows ROWS
  FETCH NEXT :NbrOfRows + 1 ROWS ONLY; 

Table @SOP:

|SOPSEQ   |SOPNBR |SOPSTS |     
|111      |123    |Review |          
|222      |456    |Review |          
|333      |789    |Review |   

Table @SOPREV:

|SOPSEQ   |REVUSR2 |  
|111      |Mark    |         
|111      |John    |         
|333      |Erik    |   

回答1:


I'm not entirely sure about what exactly you want, but if you want the count from the first table only, you can get it using COUNT(DISTINCT column) as shown below:

select
  a.sopseq,
  a.sopnbr,
  b.revusr2, 
  count(distinct a.sopseq) as aaa
from sop a
inner join soprev b on b.sopseq = a.sopseq
where upper(a.sopsts) = 'IN REVIEW' and upper(b.revsts) = 'IN REVIEW'
group by a.sopseq, a.sopnbr, b.revusr2
order by a.sopnbr, a.sopseq

Result:

SOPSEQ  SOPNBR  REVUSR2  AAA
------  ------  -------  ---
   111     123  Mark       1
   111     123  john       1
   333     789  Erik       1

For reference, the data script I used is:

create table sop (
  sopseq int,
  sopnbr int,
  sopsts varchar(10)
);

insert into sop (sopseq, sopnbr, sopsts) values 
  (111, 123, 'In Review'),
  (222, 456, 'In Review'),
  (333, 789, 'In Review');

create table soprev (
  sopseq int,
  revusr2 varchar(10),
  revsts varchar(10)
);

insert into soprev (sopseq, revusr2, revsts) values
  (111, 'Mark', 'In Review'),
  (111, 'john', 'In Review'),
  (333, 'Erik', 'In Review');



回答2:


Try LEFT JOIN instead of INNER JOIN

   SELECT A.SOPSEQ, A.SOPNBR, B.REVUSR2 , COUNT(A.SOPSEQ) OVER() AS AAA
   FROM @SOP A
   LEFT JOIN @SOPREV B on A.SOPSEQ = B.SOPSEQ 
   WHERE UPPER(A.SOPSTS) = 'IN REVIEW' AND UPPER(B.REVSTS) = 'IN REVIEW'
   GROUP BY A.SOPSEQ, A.SOPNBR, B.REVUSR2
   ORDER BY A.SOPNBR, A.SOPREV

This will return count from table @SOP.



来源:https://stackoverflow.com/questions/59656144/db2-sql-count-result-from-first-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!