count column in SQL and obtain condition - java

I have a table with name test in Oracle, and (sal(integer),gender) are the two columns in it.
I want to get counter number where gender is male, sal betwwen 1000,3000.
For example: If I have three people in table test (two male ,one female) and person1 sal =1000, person2 sal = 2020, person3 sal = 1040
The return value of sql statement will be equals (2).
The variable will store return value from java.

you actually want to count rows not column, as per what i understood from ur question. then you can use count(column_name) function of SQL along with the conditions (where clause).
Query: SELECT COUNT(*) "Count" FROM test WHERE gender='male' AND salary BETWEEN 1000 AND 3000

try this query,
select count(*) from <table_name> where gender='male' and salary between 1000 to 3000;

Related

Oracle Query - Filter and Limit in two tables using JOIN

I am facing an issue in Oracle Query to achieve the following use case,
Consider I have two tables :
Table 1 : product
productId - Integer - primaryKey
productName - Varchar
Table 2 : product_sequence
productId - Integer - primaryKey
sequenceId - Integer - primaryKey
orderId - Integer
orderName - Varchar
product table has 1000 entries and product_sequence table has 10K entries
Requirement :
(paginate) fetch the entries from 0 to 100 / 100 to 200 / etc., in the product table
Distinct count of productId for showing the pagination in UI (check the sample query below)
Filter by 'productName' in 'product' table and 'orderName' in 'product_sequence' table
Query (tried) :
SELECT
p.productId, p.productName, ps.orderId, ps.orderName,
COUNT(distinct p.productId) OVER () AS TOTAL
FROM (
select *
from product
OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY
) p
JOIN product_sequence ps on p.productId=ps.productId
WHERE ps.orderId IN ('12','13','14');
NOTE : the above query will work in Oracle, But the issue is
Expected:
Return 100 entries from 'product' table with mapped entries in the 'product_sequence' table
Actual :
It first LIMITS 100 entries in product and then filter the orderId so the number of entries returned is reduced from 100 to lesser number
I agree my query is not correct: It first LIMIT by 100 in 'product' table in subquery and then goes for filter in second table which reduces the count
Could some one help me with the query for this please? Anyhelp is appreciated.
If my question is not clear, Let me know, I can explain with more info.
Try to move the OFFSET and FETCH clauses to the outer query, something like this:
SELECT q.productId, q.productName, q.orderId, q.orderName,
COUNT(distinct p.productId) OVER () AS TOTAL
FROM ( SELECT * FROM product p JOIN product_sequence ps ON p.productId = ps.productId
WHERE ps.orderId IN ('12','13','14') ) q
OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY
To get 100 rows per page "after filtering" you'll need to find all the productid values first, then process the main query.
For example:
select
p.productid, p.productname, ps.orderid, ps.orderName,
count(distinct p.productid) over() as total
from product p
join product_sequence ps on p.productid = ps.productid
where ps.orderid in ('12','13','14')
and p.productid in (
select *
from (
select distinct p.productid
from product p
join product_sequence ps on p.productid = ps.productid
where p.productname like '%theremin%' -- filter #1
and ps.orderid in ('12','13','14') -- filter #2
) x
order by productid
offset 300 rows -- get the 4th page
fetch first 100 rows only -- page size set to 100 rows
)
See example at db<>fiddle.

How to define default where clause on a table in oracle

There are some query that have same part of where clause on.
Query one:
select [some-selected column]
from [TABLE_NAME]
where [its-own-where-clause]
and [shared-where-clause]
Query two:
select [some-selected column]
from [TABLE_NAME]
where [its-own-where-clause]
and [shared-where-clause]
Query three:
select [some-selected column]
from [TABLE_NAME]
where [its-own-where-clause]
and [shared-where-clause]
.
.
.
.
Query n:
select [some-selected column]
from [TABLE_NAME]
where [its-own-where-clause]
and [shared-where-clause]
As you can see there are two parts in the where-clause, the first one is belong to its own business of query and the second one is shared between all of these querys.
It is clear that the all of above query must be changed when [shared-where-clause] is changed.
I want to put the shared-section of where-clause in which the change of it is applied to all of this querys.
Is it possible in oracle?
Create a VIEW.
Example:
create table PERSON (
PERSON_ID number(10, 0) not null primary key,
PERSON_NAME nvarchar(100) not null,
AGE number(3, 0) not null,
GENDER char(1) not null check(GENDER in ('M', 'F'))
);
create view MALES as
select PERSON_ID, PERSON_NAME, AGE, GENDER
from PERSON
where GENDER = 'M';
create view FEMALES as
select PERSON_ID, PERSON_NAME, AGE, GENDER
from PERSON
where GENDER = 'F';
Now we can query various age groups of male persons without repeating the shared condition on GENDER.
select *
from MALES
where AGE between 0 and 19;
select *
from MALES
where AGE between 20 and 49;
select *
from MALES
where AGE >= 50;

SQL query Help about Datetime type

I want to write a time check. That is 1 customer can't deposit more than 5 times 1 days. I just wrote this to check:
SELECT CUSTOMERID
FROM TRANSACTIONS
WHERE (SELECT DATEPART(HOUR,GETDATE())) BETWEEN ((SELECT DATEPART(HOUR,GETDATE()))-24) AND (SELECT DATEPART(HOUR,GETDATE()))
AND METHODID = 1
AND CUSTOMERID = 8
To count customer and check if >5 return false. But i think it's wrong. Anyone help me the query about hour and date ( Column Date is DATETIME type)
Here the image of my table.
As per my understanding, You have a customer ID and wanna check the number of transaction in a day of that customer and allow it for the transaction if count is less than 5. So try the following query.(Query will return "true" if transactions<5 else "false").
select case when count(*) < 5 then 'True' else 'False' end from [YOUR_TABLE_NAME]
where CUSTOMERID = 8
and cast([YOUR_DATE_COLUMN_NAME] as date)=cast(GETDATE() as date)
You need aggregate function count, group by clause and case when for checking
If your dbms is Mysql then below query will help you
select customerid,date(date) as date_of_month,
case when count(transactionid)>5 then 'false' else 'True'
from TRANSACTIONS
group by customerid,date(date)
If your dbms is mssql server
select customerid,convert(date,[date]) as date_of_month,
case when count(transactionid)>5 then 'false' else 'True'
from TRANSACTIONS
group by customerid,convert(date,[date])

Getting a count for each duplicate record in response from SQL query

I have four columns, 2 columns lets say FIRST_NAME and LAST_NAME in table PersonalInfo and other 2 columns ADD1 and ADD2 in table AddressDetails. Now what I have to do is I want to know the count for duplicate record for each row considering all 4 columns.How can I do that?
I have 2 approach till now:
1. I iterate each response and compare with the remaining.
2. Do something with query.
I know the first case is worst option because it will take so much of the time. Is there something I can do with query?
I searched and found this:
SELECT LAST_NAME, count(LAST_NAME) FROM SchemaName.PersonalInfo S GROUP by LAST_NAME;
and the basic is working for single column and not for multiple columns.
How can I do it. Please suggest.
Group by all the cols not just last name.
Working fiddle : http://sqlfiddle.com/#!9/a76e7e/3
SELECT P.fname,P.lname,A.add1,A.add2, count(*)
FROM PersonalInfo P, AddressDetails A
Where P.id = A.id
GROUP by P.fname,P.lname,A.add1,A.add2
having count(*) > 1;
Join you tables on the id like in above example.
I suppose you table PersonalInfo has a primary key and AddressDetails ha a forey key on this primary key ?
select t1.FIRST_NAME , t1.LAST_NAME, t2.ADD1 , t2.ADD2, count(*) NbPossibility
from PersonalInfo t1 inner join AddressDetails t2
on t1.idPersonalInfo=t2.idPersonalInfo
group by t1.FIRST_NAME , t1.LAST_NAME, t2.ADD1 , t2.ADD2
having count(*)>1
Il you have not keys for join this tables (anormal):
select t1.FIRST_NAME , t1.LAST_NAME, t2.ADD1 , t2.ADD2, count(*) NbPossibility
from PersonalInfo t1 cross join AddressDetails t2
group by t1.FIRST_NAME , t1.LAST_NAME, t2.ADD1 , t2.ADD2
having count(*)>1

dynamic variable value jasper report

I don't know how to title this question and I know it's just a simple and stupid logic need to be sorted out but I can explain what I need. I have a jasper report script and query in which I need a simple calculation based on a value gathered from Query below
SELECT TOTAL, PARTIAL FROM PRICE WHERE TOTAL > 0
now I need this value to be calculated as the expression below in jasper report script
VAR CALC += TOTAL + (PARTIAL) //as partial can be a -ve or +ve value
What's happening currently is that I didn't find a way to do this, whenever I assign value of TOTAL to a variable and try to use it, it always get's the value from Query and calculates, while I need it to be there only once and then perform calculation on it onward. For that I tried to use calculation="First" but that also gives the first value for all the time and continues. I hope I am able to put my problem well, please help
EDIT
QUERY
SELECT RECEIPTS.DATENEW AS DATE,
TICKETS.TICKETID AS TICKETID,
PAYMENTS.PAYMENT AS PAYMENT,
PAYMENTS.METHOD AS METHOD,
PAYMENTS.TOTAL AS TOTAL,
CUSTOMERS.NAME AS NAME,
(SELECT SUM(P.TOTAL) FROM PAYMENTS AS P
INNER JOIN RECEIPTS AS R ON P.RECEIPT = R.ID
INNER JOIN TICKETS AS T ON R.ID = T.ID
INNER JOIN CUSTOMERS AS C ON T.CUSTOMER = C.ID
WHERE C.ID = CUSTOMERS.ID and P.PAYMENT IN ('debt','debtpaid', 'advance', 'cashrefund')) AS CTOTAL
FROM RECEIPTS
INNER JOIN TICKETS ON RECEIPTS.ID = TICKETS.ID
INNER JOIN PAYMENTS ON RECEIPTS.ID = PAYMENTS.RECEIPT
INNER JOIN CUSTOMERS ON TICKETS.CUSTOMER = CUSTOMERS.ID
WHERE
PAYMENTS.PAYMENT IN ('debt', 'debtpaid', 'advance', 'cashrefund')
....
....
WHERE -TOTAL > 0
VARIABLE
<variable name="DUES" class="java.lang.Double" resetGroup="Customer" resetType="Group" calculation="Nothing">
<variableExpression><![CDATA[$F{CTOTAL} + $F{TOTAL}]]></variableExpression>
<initialValueExpression><![CDATA[new Double(0.0)]]></initialValueExpression>
</variable>
OUTPUT
You can define the variable itself in SQL statement like this :-
SELECT SUM(#csum := #csum + TOTAL+PARTIAL)
FROM (SELECT TOTAL, PARTIAL,#csum := 0
FROM PRICE WHERE TOTAL > 0
) a;
See this question and answer

Categories

Resources