New table with row counts - sql

I have 5 different tables stored in Hive, and I would like to know how to create a new table, called total_counts which has 5 columns each with the total row count from the individual tables. So, something like
My data is road flights for each year from 2015 to 2019, so I would like a table which just gives me the total number of accidents in each year.
I have tried variations of the following:
create table total_counts
as select COUNT(*)
from flights_2014 as "2014_count", flights_2015 as "2015_count;
I can get the counts for an individual year, but I can't seem to give the columns a heading, nor can I figure out how to do it for all my tables.
Thanks.

Calculate counts in sub-queries and do cross joins if you want to store data in columns
CREATE TABLE total_counts AS
SELECT 2015_count.cnt as 2015_count, 2016_count.cnt as 2016_count, ...
FROM (SELECT COUNT(*) cnt FROM flights_2015) AS 2015_count
CROSS JOIN
(SELECT COUNT(*) cnt FROM flights_2016) AS 2016_count
...
Or the same using UNION ALL + aggregation:
CREATE TABLE total_counts AS
SELECT max(case when yr=2015 then cnt else 0 end) 2015_count,
max(case when yr=2016 then cnt else 0 end) 2016_count,
...
FROM (
SELECT COUNT(*) cnt, 2015 yr FROM flights_2015
UNION ALL
SELECT COUNT(*) cnt, 2016 yr FROM flights_2016
...
) u

CREATE TABLE total_counts AS
SELECT
(SELECT COUNT(*) FROM flights_2015) AS 2015_count,
(SELECT COUNT(*) FROM flights_2016) AS 2016_count;
etc.

Related

SQL - Group by group property?

I've got a table of consignments (simplified of course)
CONSIGNMENT_NR CUSTOMER
1 1
2 1
3 2
4 2
5 2
I can easily select, for each customer, how many consignments they have:
SELECT CUSTOMER, COUNT(*) AS 'Count'
FROM CONSIGNMENT
GROUP BY CUSTOMER
Which will give me (with that example data):
CUSTOMER Count
1 2
2 3
But what I want is to get how many customers made x amount of consignments.
The data I want would look like this:
Amount No of Customers
2 1
3 1
I can't quite figure out how.
Wrap your query up as a derived table. GROUP BY its result:
select Amount, count(*) as No_of_Customers
from
(
SELECT COUNT(*) AS Amount
FROM CONSIGNMENT
GROUP BY CUSTOMER
) dt
group by Amount
you can try below - using subquery
select count(distinct customer) as noofcustomer, 'Count'
from
(
SELECT CUSTOMER, COUNT(*) AS 'Count'
FROM CONSIGNMENT
GROUP BY CUSTOMER
)A group by 'Count'

Query 2 sum in 1 table

table a
column id : a a b b
column total : 1 2 1 3
how can i show? in one table without use compute
a 3 7
b 4 7
Do group by to sum each id's total. Do a sub-select to count total:
select id,
sum(total) as total,
(select sum(total) from a) as totalall
from a
group by id
Using window functions with a distinct, it can be simply expressed like this:
select distinct id,
sum(Total) over(partition by id) total,
Sum(Total) over () total_all
from mytable
SQL Fiddle
One way is to use OUTER APPLY. You could also set a variable to the sum of the table and call that variable.
select a.id, sum(a.total) as total, b.Grand as GrandTotal
from tablea a
outer apply
(select sum(total) as Grand from tablea) b
group by a.id

Display multiple count values on joined tables

I am trying to get a count of the userID's that exist in 2 tables,
I also have an inner join for the tables on the userID so that I can search for the count of one table, based off the BadgeID from the other table.
So far it returns the user count for one table, but I can't seem to figure out how to return a count for userID on both tables, Any suggestions?
SELECT DISTINCT live_event.usid, COUNT(1) AS membercount
FROM live_event
INNER JOIN member_badges ON live_event.usid = member_badges.usid
WHERE bdgid = 14
Not sure what you are looking for; but based on what I could understand, are sub-queries perhaps the route you are wanting to go?
select
(select count(*) from firsttable where userid = {userid})
as count1,
(select count(*) from secondtable where userid = {userid})
as count2
Where {userid} would be your bdgid.
Try to use union select to connect results from two tables
select useid, count(*) from (
select useid from firsttable
union select useid from second table ) group by useid
Try this:
SELECT
user_id,
COALESCE(MAX(
CASE
when tbl_name='live_event' then cnt_records
else null
END), 0) as cnt_live_event,
COALESCE(MAX(CASE
when tbl_name='member_badges' then cnt_records
else null
END), 0) as cnt_member_badges
FROM
(
SELECT
'live_event' AS tbl_name,
usid as user_id,
count(*) AS cnt_records
FROM live_event
GROUP BY 'live_event', usid
UNION
SELECT
'member_badges',
usid as user_id,
count(*)
FROM member_badges
GROUP BY 'member_badges', usid
) grouped_counts
GROUP BY user_id
ORDER BY user_id;
The above query would get you the user counts even if the usid is present in only one of the tables.

How to combine two tables into own this the same columns?

I have two tables A and B. A has two columns: id, amount. B also has two columns: id, amount.
I hope to combine A and B to create a new table C, with same two columns:id, amount. How can I do it using SQL?
For example:
A
('A1',1)
('A2',5)
('A3',2)
('A4',5)
('A5',2)
('A6',7)
B
('A1',3)
('A3',2)
('A4',7)
('A5',4)
('A8',2)
('A9',10)
so C should be:
C
('A1',4)
('A2',5)
('A3',4)
('A4',12)
('A5',6)
('A6',7)
('A8',2)
('A9',10)
SELECT ID, SUM(Amount) total
FROM
(
SELECT ID, Amount FROM A
UNION ALL
SELECT ID, AMount FROM B
) s
GROUP BY ID
SQLFiddle Demo
You can create a table base on the result from the query.
CREATE TABLE C
AS
SELECT ID, SUM(Amount) total
FROM
(
SELECT ID, Amount FROM A
UNION ALL
SELECT ID, AMount FROM B
) s
GROUP BY ID;
SQLFiddle Demo
the answer above works absolutely fine. Just to add to it an order by clause that will sort by ID.
SELECT ID, SUM(Amount) as total
FROM
(
SELECT ID, Amount FROM A
UNION ALL
SELECT ID, AMount FROM B
) s
GROUP by ID
order by ID

SUM of grouped COUNT in SQL Query

I have a table with 2 fields:
ID Name
-- -------
1 Alpha
2 Beta
3 Beta
4 Beta
5 Charlie
6 Charlie
I want to group them by name, with 'count', and a row 'SUM'
Name Count
------- -----
Alpha 1
Beta 3
Charlie 2
SUM 6
How would I write a query to add SUM row below the table?
SELECT name, COUNT(name) AS count
FROM table
GROUP BY name
UNION ALL
SELECT 'SUM' name, COUNT(name)
FROM table
OUTPUT:
name count
-------------------------------------------------- -----------
alpha 1
beta 3
Charlie 2
SUM 6
SELECT name, COUNT(name) AS count, SUM(COUNT(name)) OVER() AS total_count
FROM Table GROUP BY name
Without specifying which rdbms you are using
Have a look at this demo
SQL Fiddle DEMO
SELECT Name, COUNT(1) as Cnt
FROM Table1
GROUP BY Name
UNION ALL
SELECT 'SUM' Name, COUNT(1)
FROM Table1
That said, I would recomend that the total be added by your presentation layer, and not by the database.
This is a bit more of a SQL SERVER Version using Summarizing Data Using ROLLUP
SQL Fiddle DEMO
SELECT CASE WHEN (GROUPING(NAME) = 1) THEN 'SUM'
ELSE ISNULL(NAME, 'UNKNOWN')
END Name,
COUNT(1) as Cnt
FROM Table1
GROUP BY NAME
WITH ROLLUP
Try this:
SELECT ISNULL(Name,'SUM'), count(*) as Count
FROM table_name
Group By Name
WITH ROLLUP
all of the solution here are great but not necessarily can be implemented for old mysql servers (at least at my case). so you can use sub-queries (i think it is less complicated).
select sum(t1.cnt) from
(SELECT column, COUNT(column) as cnt
FROM
table
GROUP BY
column
HAVING
COUNT(column) > 1) as t1 ;
Please run as below :
Select sum(count)
from (select Name,
count(Name) as Count
from YourTable
group by Name); -- 6
The way I interpreted this question is needing the subtotal value of each group of answers. Subtotaling turns out to be very easy, using PARTITION:
SUM(COUNT(0)) OVER (PARTITION BY [Grouping]) AS [MY_TOTAL]
This is what my full SQL call looks like:
SELECT MAX(GroupName) [name], MAX(AUX2)[type],
COUNT(0) [count], SUM(COUNT(0)) OVER(PARTITION BY GroupId) AS [total]
FROM [MyView]
WHERE Active=1 AND Type='APP' AND Completed=1
AND [Date] BETWEEN '01/01/2014' AND GETDATE()
AND Id = '5b9xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' AND GroupId IS NOT NULL
GROUP BY AUX2, GroupId
The data returned from this looks like:
name type count total
Training Group 2 Cancelation 1 52
Training Group 2 Completed 41 52
Training Group 2 No Show 6 52
Training Group 2 Rescheduled 4 52
Training Group 3 NULL 4 10535
Training Group 3 Cancelation 857 10535
Training Group 3 Completed 7923 10535
Training Group 3 No Show 292 10535
Training Group 3 Rescheduled 1459 10535
Training Group 4 Cancelation 2 27
Training Group 4 Completed 24 27
Training Group 4 Rescheduled 1 27
You can use union to joining rows.
select Name, count(*) as Count from yourTable group by Name
union all
select "SUM" as Name, count(*) as Count from yourTable
For Sql server you can try this one.
SELECT ISNULL([NAME],'SUM'),Count([NAME]) AS COUNT
FROM TABLENAME
GROUP BY [NAME] WITH CUBE
with cttmp
as
(
select Col_Name, count(*) as ctn from tab_name group by Col_Name having count(Col_Name)>1
)
select sum(ctn) from c
You can use ROLLUP
select nvl(name, 'SUM'), count(*)
from table
group by rollup(name)
Use it as
select Name, count(Name) as Count from YourTable
group by Name
union
Select 'SUM' , COUNT(Name) from YourTable
I am using SQL server and the following should work for you:
select cast(name as varchar(16)) as 'Name', count(name) as 'Count'
from Table1
group by Name
union all
select 'Sum:', count(name)
from Table1
I required having count(*) > 1 also. So, I wrote my own query after referring some the above queries
SYNTAX:
select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where {some condition} group by {some_column} having count(`table_name`.`id`) > 1) as `tmp`;
Example:
select sum(count) from (select count(`table_name`.`id`) as `count` from `table_name` where `table_name`.`name` IS NOT NULL and `table_name`.`name` != '' group by `table_name`.`name` having count(`table_name`.`id`) > 1) as `tmp`;
You can try group by on name and count the ids in that group.
SELECT name, count(id) as COUNT FROM table group by name
After the query, run below to get the total row count
select ##ROWCOUNT
select sum(s) from
(select count(Col_name) as s from Tab_name group by Col_name having count(*)>1)c