简体   繁体   中英

sql how to select count of multiple rows where row = value

hi im making a sql select for the count of multiple row values where Domain == 'whatever'.

at the moment im making 5 seperate selects which take long to load and are inefficient, im asking if and how i can select the count of multiple rows in one query or atleast more efficiently than im doing now.

i am trying to select the count of rows: route, browser, device, location and referrer where the domain is equal to "whatever"

i would like the output to contain all the listed rows above in a format like this: rowname: {count: 1}

here is the table:

CREATE TABLE IF NOT EXISTS hits (
    ID INTEGER PRIMARY KEY AUTO_INCREMENT,
    Domain TEXT NOT NULL,
    Route TEXT NOT NULL,
    Timestamp INTEGER NOT NULL,
    Browser TEXT,
    Location TEXT,
    Device TEXT,
    Referrer TEXT
)

and these are the selects i have at the moment:

    routes = db.run('SELECT Route, COUNT(Route) AS count FROM hits WHERE Domain = %s AND Timestamp BETWEEN %s AND %s GROUP BY Route', (domain, d1, d2))

    browsers = db.run('SELECT Browser, COUNT(Browser) AS count FROM hits WHERE Domain = %s AND Timestamp BETWEEN %s AND %s GROUP BY Browser', (domain, d1, d2))

    locations = db.run('SELECT Location, COUNT(Location) AS count FROM hits WHERE Domain = %s AND Timestamp BETWEEN %s AND %s GROUP BY Location', (domain, d1, d2))


    screens = db.run('SELECT Device, COUNT(Device) AS count FROM hits WHERE Domain = %s AND Timestamp BETWEEN %s AND %s GROUP BY Device', (domain, d1, d2))


    referrals = db.run('SELECT Referrer, COUNT(Referrer) AS count FROM hits WHERE Domain = %s AND Timestamp BETWEEN %s AND %s GROUP BY Referrer', (domain, d1, d2))```

The following works in SQL fiddle. The question is tagged with mysql and python, so please specify further what engine you are using if you need further assistance:

SELECT
  COUNT(Route) AS route_count, 
  COUNT(Browser) AS browser_count,
  COUNT(Location) AS location_count,
  COUNT(Device) AS device_count,
  COUNT(Referrer) AS referrer_count

FROM 
  hits 
WHERE 
  Domain = 'whatever'
  AND Timestamp BETWEEN '00:00' AND '12:00'

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