SQL Query required where we should not used the group by and data count based on dep_id - group-by

Need your help in getting the SQL Query.
1. I have one table which is having following columns
Name Null? Type
------------ -------- ------------
EMP_ID NOT NULL NUMBER(2)
DEP_ID NUMBER(2)
SALARY NUMBER(14,3)
NAME1 VARCHAR2(50)
NAME2 VARCHAR2(50)
JOINING_DATE DATE
Now I want the result - COUNT(1) based on DEP_ID without using GROUP BY .
EXAMPLE :
select DEP_ID,COUNT(1) from unipartemp group by DEP_ID;
DEP_ID COUNT(1)
1 2
2 2
3 1
What is the Query where we should get the same result but we should not use group by ...
Please suggest .

I am assuming that the result u r looking for is the count of the distinct dept_id. Try using the distinct(dept_id) to get the result.

Related

include in result set columns the 5 returned columns in a User Defined Table Function

I have a UDTF that will always return 1 row of 6 columns
The UDTF has one parameter
I want the 5 columns included in the result set of a query. The table I'm querying has a column that I want to use as the parameter for each row
I have not been able to figure out the correct syntax.
Any suggestions?
The UDTF
create function xxxx.UF_yyyyyy(USERID CHAR(10))
returns table (
p2User char(10),
STATUS CHAR(3),
USED DEC(7, 0),
CREATED DEC(7, 0),
SIGNON DEC(7, 0),
EXCLUDE DEC(7, 0))
language RPGLE
NOT DETERMINISTIC
NO SQL
DISALLOW PARALLEL
NOT FENCED
EXTERNAL NAME 'xxxx/UF_yyyyyy'
PARAMETER STYLE DB2SQL
example
select * from table(xxxx/UF_yyyyyy(CHAR('CMFIRST '))) a
result
P2USER STATUS USED CREATED SIGNON EXCLUDE
---------- ------ ------- ------- ------- -------
CMFIRST ACT 1170926 1150826 1170926 0
Here is an example of a select I tried
SELECT T1.AQABVN, T1.AQA8TX,
(SELECT COUNT(*) FROM fffff T4 WHERE T4.BDABVN = T1.AQABVN) AS SACCMS,
t2.p2User, t2.used
FROM
zzzzz T1
full join table(xxxx.UF_yyyyyy(T1.AQABVN)) t2 on T1.AQABVN = t2.p2User
Result
[SQL0205] Column P2USER not in table T2 in *N.
Got it working
SELECT T1.AQABVN, T1.AQA8TX,
(SELECT COUNT(*) FROM fffff T4 WHERE T4.BDABVN = T1.AQABVN) AS SACCMS,
t2.status, t2.used, t2.created, t2.signon, t2.exclude
FROM
zzzzz T1
join
table(SMLFQA.UF_XAJKUPR(T1.AQABVN)) t2 on T1.AQABVN = t2.p2User

Need to select average age of employees department wise

I have a table in Postgresql DB. It has 3 fields: Emp_Name, Dept & Age. I need to show Average age of employees department wise. I need to display all 3 fields in the result-set. Below is the input and expected output:
Here is the SQL Fiddle : http://sqlfiddle.com/#!15/7c4cf
How do I show the expected result in PostgreSQL?
You can use the string_agg function to concatinate the employee names and avg to get the average age:
SELECT STRING_AGG(emp_name, ','), dept, AVG(age)
FROM test1
GROUP BY dept
SQLFiddle
You can use group by on Dept and use avg and string_agg aggregate functions to get the desired result:
select
string_agg(Emp_Name, ',') Emp_Name,
Dept,
avg(Age) Average_age
from test1
group by Dept;

How can I SUM distinct records in a Postgres database where there are duplicate records?

Imagine a table that looks like this:
The SQL to get this data was just SELECT *
The first column is "row_id" the second is "id" - which is the order ID and the third is "total" - which is the revenue.
I'm not sure why there are duplicate rows in the database, but when I do a SUM(total), it's including the second entry in the database, even though the order ID is the same, which is causing my numbers to be larger than if I select distinct(id), total - export to excel and then sum the values manually.
So my question is - how can I SUM on just the distinct order IDs so that I get the same revenue as if I exported to excel every distinct order ID row?
Thanks in advance!
Easy - just divide by the count:
select id, sum(total) / count(id)
from orders
group by id
See live demo.
Also handles any level of duplication, eg triplicates etc.
You can try something like this (with your example):
Table
create table test (
row_id int,
id int,
total decimal(15,2)
);
insert into test values
(6395, 1509, 112), (22986, 1509, 112),
(1393, 3284, 40.37), (24360, 3284, 40.37);
Query
with distinct_records as (
select distinct id, total from test
)
select a.id, b.actual_total, array_agg(a.row_id) as row_ids
from test a
inner join (select id, sum(total) as actual_total from distinct_records group by id) b
on a.id = b.id
group by a.id, b.actual_total
Result
| id | actual_total | row_ids |
|------|--------------|------------|
| 1509 | 112 | 6395,22986 |
| 3284 | 40.37 | 1393,24360 |
Explanation
We do not know what the reasons is for orders and totals to appear more than one time with different row_id. So using a common table expression (CTE) using the with ... phrase, we get the distinct id and total.
Under the CTE, we use this distinct data to do totaling. We join ID in the original table with the aggregation over distinct values. Then we comma-separate row_ids so that the information looks cleaner.
SQLFiddle example
http://sqlfiddle.com/#!15/72639/3
Create custom aggregate:
CREATE OR REPLACE FUNCTION sum_func (
double precision, pg_catalog.anyelement, double precision
)
RETURNS double precision AS
$body$
SELECT case when $3 is not null then COALESCE($1, 0) + $3 else $1 end
$body$
LANGUAGE 'sql';
CREATE AGGREGATE dist_sum (
pg_catalog."any",
double precision)
(
SFUNC = sum_func,
STYPE = float8
);
And then calc distinct sum like:
select dist_sum(distinct id, total)
from orders
SQLFiddle
You can use DISTINCT in your aggregate functions:
SELECT id, SUM(DISTINCT total) FROM orders GROUP BY id
Documentation here: https://www.postgresql.org/docs/9.6/static/sql-expressions.html#SYNTAX-AGGREGATES
If we can trust that the total for 1 order is actually 1 row. We could eliminate the duplicates in a sub-query by selecting the the MAX of the PK id column. An example:
CREATE TABLE test2 (id int, order_id int, total int);
insert into test2 values (1,1,50);
insert into test2 values (2,1,50);
insert into test2 values (5,1,50);
insert into test2 values (3,2,100);
insert into test2 values (4,2,100);
select order_id, sum(total)
from test2 t
join (
select max(id) as id
from test2
group by order_id) as sq
on t.id = sq.id
group by order_id
sql fiddle
In difficult cases:
select
id,
(
SELECT SUM(value::int4)
FROM jsonb_each_text(jsonb_object_agg(row_id, total))
) as total
from orders
group by id
I would suggest just use a sub-Query:
SELECT "a"."id", SUM("a"."total")
FROM (SELECT DISTINCT ON ("id") * FROM "Database"."Schema"."Table") AS "a"
GROUP BY "a"."id"
The Above will give you the total of each id
Use below if you want the full total of each duplicate removed:
SELECT SUM("a"."total")
FROM (SELECT DISTINCT ON ("id") * FROM "Database"."Schema"."Table") AS "a"
Using subselect (http://sqlfiddle.com/#!7/cef1c/51):
select sum(total) from (
select distinct id, total
from orders
)
Using CTE (http://sqlfiddle.com/#!7/cef1c/53):
with distinct_records as (
select distinct id, total from orders
)
select sum(total) from distinct_records;

counting in sql in subquery in the table

DNO DNAME
----- -----------
1 Research
2 Finance
EN ENAME CITY SALARY DNO JOIN_DATE
-- ---------- ---------- ---------- ---------- ---------
E1 Ashim Kolkata 10000 1 01-JUN-02
E2 Kamal Mumbai 18000 2 02-JAN-02
E3 Tamal Chennai 7000 1 07-FEB-04
E4 Asha Kolkata 8000 2 01-MAR-07
E5 Timir Delhi 7000 1 11-JUN-05
//find all departments that have more than 3 employees.
My try
select deptt.dname
from deptt,empl
where deptt.dno=empl.dno and (select count(empl.dno) from empl group by empl.dno)>3;
here is the solution
select deptt.dname
from deptt,empl
where deptt.dno=empl.dno
group by deptt.dname having count(1)>3;
select
*
from departments d
inner join (
select dno from employees group by dno having count(*) > 3
) e on d.dno = e.dno
There are many approaches to this problem but almost all will use GROUP BY and the HAVING clause. That clause allows you to filter results of aggregate functions. Here it is used to choose only those records where the count is greater than 3.
In the query structure used above the group by is handled on the employee table only, then the result (which is known as a derived table) is joined by an INNER JOIN to the departments table. This inner join only allows matching records so this has the effect of filtering the departments table to only those which have a count() of greater than 3.
An advantage of this query structure is fewer records are joined, and also that all columns of the departments table are available for reporting. Disadvantage of this structure is the the count() of employees per department isn't visible.

Merge multiple queries excluding common results

Data :
--Table 1 :
Id ZoneName
----------- --------
20011 Name1
10027 Name1
20011 Name1
20011 Name1
20011 Name1
20074 Name1
20011 Name2
20011 Name2
10059 Name3
20011 Name2
Query :
Select Top 2 [Id] From Table1 -- First Query
WHERE ZoneName = 'Name1'
UNION
SELECT Top 1 [Id] from Table1 -- Second Query
WHERE ZoneName = 'Name1'
UNION
SELECT Top 1 [Id] from Table1 -- Third Query
WHERE ZoneName = 'Name1'
Result :
Id
-----
20011
Expected Result :
20011
10027
20074
From the above query I need 3 results from each query that do NOT overlap each other, in this case the expected result should contain the top 2 for query 1 i.e. 20011 and 10027 and for the next top 1 it should exclude those 2 results and return 20074 for query 2.
Note : I have used a single WHERE condition for this example, however in the actual query each of the query has different Where conditions, and could end up having same / different result from the query above itself.
As far as I know If you are searching to query distinct Id's for a particular ZoneName then this may work out
SELECT DISTINCT ID
FROM TABLE1
WHERE ZoneName="Name1"