Query a list of CITY names from STATION for cities that have an even ID number. Print the results in any order, but exclude duplicates from the answer.
The STATION table is described as follows:
CREATE TABLE STATION
(
Id int,
CITY varchar(50),
STATE varchar(50),
LAT_N int,
LONG_W int
)
I have this SQL which throws an error when I run:
SELECT CITY, STATE
FROM STATION
WHERE ID % 2 = 0
GROUP BY ID, CITY, STATE
There is no need to group by ID
select CITY,STATE from STATION where (ID % 2)=0 group by CITY,STATE
But you don't need a grouping function, DISTINCT will do also the trick
select DISTINCT CITY, STATE from STATION where (ID % 2)=0
Related
I'm very new to Maria db but I haven't found a solution to this problem. I have a database with several tables. Two of the tables are employees and customers. They have no relation to each other.
create table clients (id int, name varchar(50), city varchar (20))
create table workers (id int, name varchar (50), city varchar(20))
I'm trying to write a select query that will return the name of a city, the total number of workers, and the total number of clients in that city. The clients table has over 2000 entries and the workers table has 60.
The problem is that if I do this:
Select workers.id, clients.id from workers, clients;
I get 120,000 rows (60 * 2000). How do I achieve my goal?
Sorry if the formatting is weird.
You can use union all and group by:
select city, sum(num_clients) as num_clients,
sum(num_workers) as num_workers
from ((select city, count(*) as num_clients, 0 as num_workers
from clients
group by city
) union all
(select city, 0 as num_clients, count(*) as num_workers
from workers
group by city
)
) c
group by city;
Here's what you need.
select
t1.city,
sum(t1.workers),
sum(t1.clients)
from
(
select
city,
1 as 'workers',
0 as 'clients'
from
workers
union all
select
city,
0 as 'workers',
1 as 'clients'
from
clients
) t1
group by
t1.city;
I have created the following table:
CREATE TABLE Student
(
StudentID int PRIMARY KEY,
Name varchar(30),
Age int,
Course varchar(30),
Year int,
Address varchar(50),
Phone varchar(12),
Email varchar(50)
);
I was wondering how to run a query to show the year level and the number of students in each year level I need only to show year levels that have at least two students.
Looks like homework assignment!
select year, count(1)
from Student
group by year
having count(1) >= 2
You can do like below. You need to group by year and count and filter where count >= 2
select year, count(*) as count from student group by year having count >= 2
SELECT Year,COUNT(StudentID) from Student GROUP BY Year having COUNT(studentID) > 2
since each student ID is for a unique student I assume you can count on them as well.
select Year, count (*) from Student
group by Year
having count(*) > 1
I am trying to figure out how to structure some queries, and I am a bit lost.
Tables:
CREATE TABLE dv_customer(
customer_id INTEGER PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(50),
address_id INTEGER,
active BOOLEAN
);
CREATE TABLE dv_address(
address_id INTEGER PRIMARY KEY,
address VARCHAR(50),
address2 VARCHAR(50),
district VARCHAR(50),
city_id INTEGER,
postal_code VARCHAR(50),
phone VARCHAR(50)
);
CREATE TYPE MPAA_RATING AS ENUM(
'G',
'PG',
'PG-13',
'R',
'NC-17'
);
CREATE TABLE dv_film(
film_id INTEGER PRIMARY KEY,
title VARCHAR(50),
description TEXT,
length SMALLINT,
rating MPAA_RATING,
release_year SMALLINT
);
CREATE TABLE cb_customers(
last_name VARCHAR(50),
first_name VARCHAR(50),
PRIMARY KEY (last_name, first_name)
);
CREATE TABLE cb_books(
title VARCHAR(50),
author_id INTEGER,
edition SMALLINT,
publisher VARCHAR(50),
PRIMARY KEY (title, author_id, edition)
);
CREATE TABLE cb_authors(
author_id INTEGER PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50)
);
CREATE TABLE mg_customers(
customer_id INTEGER PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(50),
address_id INTEGER,
active BOOLEAN
);
I need to figure out the following Queries:
What are the first and last names of all customers who live in the district having the most customers?
So far:
SELECT x.first_name, x.last_name
FROM dv_customer x, dv_address y
WHERE x.address_id = y.address_id
AND (SELECT count(district)
FROM dv_address >= SELECT count(district) FROM dv_address
);
What are the first and last names of the top 10 authors when ranked by the number of books each has written? I want author name and book count, in descending order of book count.
So far:
SELECT x.first_name, x.last_name, count(y.title)
FROM cb_authors x, cb_books y
GROUP BY first_name, last_name
ORDER BY count(*) DESC
LIMIT 10;
I know these are a bit of a mess, but they are the only queries I can't seem to figure out. Any help would be appreciated. I am a Postgres noob and just trying to figure out how it works.
What are the first and last names of the top 10 authors when ranked by the number of books each has written
This kind of query is typically done using a window function:
select first_name, last_name, num_books
from (
SELECT x.first_name, x.last_name,
dense_rank() over (order by count(y.title) desc) as rnk,
count(*) as num_books
FROM cb_authors x
join cb_books y on x.author_id = y.author_id
GROUP BY x.author_id
) t
where rnk <= 10
Your from clause FROM cb_authors x, cb_books y is missing a join condition and thus creates a cartesian join between the two tables. It is a good example on why the implicit joins in the where clause are a bad thing. If you get in the habit of using an explicit JOIN operator you will never accidentally miss a join condition.
The above also uses x.author_id which is sufficient for grouping as it is the primary key of the column and all other (non-grouped) columns in the select list are functionally dependent on it.
The query below will give you the district with the most customers
select district
from dv_address
group by district
order by count(*) desc
limit 1
Then you can select all customers living in that district with a sub query
select c.* from dv_customer c
join dv_address a on c.address_id = a.address_id
where a.district = (
select district
from dv_address
group by district
order by count(*) desc
limit 1
)
Similarly you can get the top 10 author_id's with this query
select author_id
from cb_books
group by author_id
order by count(*) desc
limit 10
Similarly, with a dervied table
select a.*, t.cnt from cb_authors a
join (
select author_id, count(*) cnt
from cb_books
group by author_id
order by count(*) desc
limit 10
) t on t.author_id = a.author_id
order by t.cnt desc
I have table with columns like AutoID, Number, Name, City, State, Country.
What I wanted is the maximum number entered in the "Number" column with the combination of Name, City, State and Country.
Example:
Name City State Country
Smith NY NY USA
John NY NY USA
John NJ NY USA
Now smith should get "Number" 1, John 2, and again John(in NJ) 1 as he is the first from NJ.
I can simply put a where clause in query and get the max number + 1. But the problem is that when I have huge amount of data and the number of users increases, my query will be really slow. I am also inserting data in the same table so it will keep on piling.
I hope I have made my self clear.
Vipul Parekh
I am guessing that this is what you want:
Name City State Country Number
Smith NY NY USA 1
John NY NY USA 2
John NJ NY USA 1
This is provided by row_number():
select name, city,state, country,
row_number() over (partition by city, state, country order by (select null)) as Number
from table t;
Note that the sequencing of the Number within a group is arbitrary, because you don't provide an id or createdat column. There is no guarantee that it is in the same order as the table, because SQL tables are inherently unordered.
You can create a trigger on your table. whenever you insert a row it will count the number of rows and update the latest one with a number with the count + 1.
To get around slowness you can create a index on Name, City, State and Country.
Let me know if you need a sample code or some pointers.
You can Use ROW_NUMBER
SELECT * FROM
(
Select Name,
City,
State,
Country,
Row_Number() over (Partition by City, State, Country ORDER BY Name) AS Number
From table1
) AS T
WORKING FIDDLE
1)
WITH Optimize_CTE (id, cityid,stateid, countryid)
AS
-- Define the CTE query.
(
SELECT id, cityid,stateid, countryid
FROM Optimize
WHERE id IS NOT NULL
)
-- Define the outer query referencing the CTE name.
SELECT id,
convert(Varchar(255),cityid) as CityId,
convert(Varchar(255),stateid) as StateId,
convert(Varchar(255),countryid) as CountryId
FROM Optimize_CTE OPTION (MAXRECURSION 1)
DECLARE #RowsPerPage INT = 10, #PageNumber INT = 1
SELECT InvoiceID, CustomerID
FROM dbo.SalesInvoice
ORDER BY InvoiceID
OFFSET (#PageNumber-1)*#RowsPerPage ROWS
FETCH NEXT #RowsPerPage ROWS ONLY
GO
How to select distinct from table including ID column on the result?
Like for example: (this is error query)
SELECT ID,City,Street from (SELECT distinct City, Street from Location)
The table Location
CREATE TABLE Location(
ID int identity not null,
City varchar(max) not null,
Street varchar(max) not null
)
Then it will show the column ID, distinct column City, distinct column Street
Is there a possible query to have this result?
If you want for instance the lowest id for the unique data you desire you can do
select min(id), City, Street
from Location
group by City, Street
Generally you have to tell the DB what id to take using an aggregate function like min() or max()