简体   繁体   中英

Select count same column but no NULL values

I have got this table:

 id akce text xyza year 61 FF1231-00 Bob NULL NULL 58 NULL 2014 62 FF1231-00 Alice NULL NULL 57 NULL 2014 57 FF1231-00 1/2 SWC 2 20 NULL NULL 2014 58 FF1231-00 1/3 SWC 3 5 NULL NULL 2014 59 FF1231-00 Jim NULL NULL 57 NULL 2014 

Now I'm trying to achieve to find how many results having column z not NULL at SUM match

table.id = table.z WHERE table.z is NOT NULL

 id akce text xyza year 57 FF1231-00 1/2 SWC 2 20 NULL 2 2014 58 FF1231-00 1/3 SWC 3 5 NULL 1 2014 

I tried to do following

SELECT T1.id, T1.text, T1.z, T1.akce, T2.[text], (SELECT COUNT(T1.z) where T1.z IS NOT NULL Group by T1.z)
FROM ubytov T1
LEFT OUTER JOIN ubytov T2
    ON T1.z = T2.id
    WHERE T1.akce='FF1231-00' AND T1.z IS NULL

But got this exception:

Each GROUP BY expression must contain at least one column that is not an outer reference.

Can you guys please help me to achieve that result?

Thanks in advance and thanks for your time.

EDIT: This query according to Fabio answer gives me desired result:

SELECT t.id
, t.akce
, t.text
, t.x
, t.y
, t.z
, qnt.Quantity
FROM ubytov t 
OUTER APPLY (SELECT COUNT(q.z) AS Quantity FROM Ubytov
q WHERE q.z = t.id) qnt WHERE t.z is NULL

As I understand you want to know how much same ID found from z column
Try CROSS APPLY (query from SQL Fiddle sample )

SELECT t.ID
, t.Akce
, t.x
, t.y
, t.z
, qnt.Quantity
FROM Test t
OUTER APPLY (SELECT COUNT(q.ID) AS Quantity FROM Test q WHERE q.z = t.ID) qnt

If you want remove rows with Quantity = 0 from result,
then change OUTER APPLY to CROSS APPLY

Try this:

SELECT T1.id, T1.text, T1.z, T1.akce, T2.[text], 
(SELECT COUNT(T3.z) FROM ubytov T3 where T3.z IS NOT NULL)
FROM ubytov T1
LEFT OUTER JOIN ubytov T2
    ON T1.z = T2.id
    WHERE T1.akce='FF1231-00' AND T1.z IS NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM