简体   繁体   中英

How to check if all instances of a DB row are the same and if so count + 1 in SQL?

I have the following SQLite DB table:

app | vendor | active
---------------------
123 |  AGX   | 1
123 |  OTMA  | 0
123 |  PEI   | 0

255 |  IYU   | 0
255 |  MAG   | 0
255 |  MEI   | 0

675 |  IUU   | 0
675 |  AGU   | 0
675 |  O3I   | 0

I need to be able to run a query to find out out of these apps, which ones have NO active vendors .

In the above example, app 255 and app 675 have no active vendors (0), therefore the return of my query should be 2 .

So far, I am only able to run a query to get the number of rows that are 'false', but not the number of apps which are false in ALL instances:

SELECT COUNT(*) FROM app_vendor WHERE active = 0

summing up: if all rows of a single app are 'false', that should add 1 to the count.

This query will give you a list of apps with NO active vendors:

SELECT app
FROM app_vendor
GROUP BY app
HAVING SUM(CASE WHEN active = true THEN 1 ELSE 0 END) = 0

To count the records you could wrap it in a subquery:

SELECT COUNT(*) FROM (
  SELECT app
  FROM app_vendor
  GROUP BY app
  HAVING SUM(CASE WHEN active = true THEN 1 ELSE 0 END) = 0
)
SELECT COUNT(*)
FROM (
      SELECT app, COUNT(*)
      FROM demo
      GROUP BY app
      HAVING MAX(active) = 0
)

So basically you create groups of your vendors by app and then check if in group the max value is false (it means true isn't present).

There should be more elegent way for it indeed.

Presumably, you have an app table with one row per app . I would recommend using this:

select a.*
from app a
where not exists (select 1
                  from app_vendor av
                  where av.app = a.app and av.active = 1
                 );

This approach has two advantages to just using the app_vendor table itself:

  1. By avoiding the outer aggregation, it is likely to be faster under many circumstances.
  2. It will return apps that have no vendors.

You need aggregation and COUNT() window function:

SELECT DISTINCT COUNT(*) OVER() AS counter
FROM app_vendor
GROUP BY app
HAVING MAX(active) = 0

See the demo .
Results:

counter
2

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