Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this query

select 
a.Des as 'Alm', 
SUM (case k.IdE when 1 then 1 else 0 end) as Normal, 
SUM (case  k.IdE when 2 then 1 else 0 end) as Urgent  
FROM TblKBA a 
left join TblKBK k 
on a.idA = k.IdAr
group by a.Des 


with this result

Alm	Normal	Urgent
U1.K1.WH1	6	5
U1.K1.WH2	9	9
U1.K2.WH3	0	0
U2.K3.WH4	0	0


i want to hide the alm row when normal or urgent are 0, in this example i want to hide the last two rows.

i want to get this result

Alm	Normal	Urgent
U1.K1.WH1	6	5
U1.K1.WH2	9	9


How i could do that?

regards

What I have tried:

i tryed to combine selects, having, where, exclude...
Posted
Updated 9-May-19 6:28am
v2

Easiest way to do this would be wrap what you have in a Common Table Expression (CTE) and then query the CTE.
To meet the normal or urgent are 0 requirement, the WHERE clause I used simply multiplied the columns because anything multiplied by 0 is 0.
SQL
; WITH cte (Alm, Normal, Urgent)
AS (
     SELECT     a.Des as 'Alm'
          ,     SUM (case k.IdE when 1 then 1 else 0 end) as Normal
          ,     SUM (case  k.IdE when 2 then 1 else 0 end) as Urgent
     FROM      TblKBA  a 
     LEFT JOIN TblKBK  k ON a.idA = k.IdAr
     GROUP BY  a.Des
)

SELECT *
FROM   cte
WHERE  ((Normal * Urgent) > 0)
 
Share this answer
 
If you want to filter out the rows where Normal and Urgent are both zero, then you can do that before you group them:
SQL
SELECT
    a.Des as 'Alm', 
    SUM(CASE k.IdE WHEN 1 THEN 1 ELSE 0 END) As Normal, 
    SUM(CASE k.IdE WHEN 2 THEN 1 ELSE 0 END) As Urgent  
FROM 
    TblKBA a 
    INNER JOIN TblKBK k 
    ON a.idA = k.IdAr
WHERE
    k.IdE In (1, 2)
GROUP BY
    a.Des
;

If you want to filter out rows where either Normal or Urgent is zero, then you can use the HAVING clause:
SQL
SELECT
    a.Des as 'Alm', 
    SUM(CASE k.IdE WHEN 1 THEN 1 ELSE 0 END) As Normal, 
    SUM(CASE k.IdE WHEN 2 THEN 1 ELSE 0 END) As Urgent  
FROM 
    TblKBA a 
    INNER JOIN TblKBK k 
    ON a.idA = k.IdAr
WHERE
    k.IdE In (1, 2)
GROUP BY
    a.Des
HAVING
    SUM(CASE k.IdE WHEN 1 THEN 1 ELSE 0 END) != 0
And
    SUM(CASE k.IdE WHEN 2 THEN 1 ELSE 0 END) != 0
;

HAVING (Transact-SQL) - SQL Server | Microsoft Docs[^]
 
Share this answer
 
Comments
jaket-cp 10-May-19 4:07am    
nice 5ed
select * from 
(select 
a.Des as 'Alm', 
SUM (case k.IdE when 1 then 1 else 0 end) as Normal, 
SUM (case  k.IdE when 2 then 1 else 0 end) as Urgent  
FROM TblKBA a 
left join TblKBK k 
on a.idA = k.IdAr
group by a.Des )A
where (A.Normal>0 and A.Urgent>0)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900