Select the sum of occurances of first alphabetical character - oracle

Hi what i need to do is create a select statement which outputs the sum of the first character in a field within the table so the output would look something like
A,12
B,0
C,20
D,14
E,0
ect...
The table is called contacts, in the above there was 12 occurrences of people whose names begin with the letter A
I hope i have explained this correctly

Let's understand this with EMP table example.
SQL> with
2 letters
3 as
4 (select chr( ascii('A')+level-1 ) letter
5 from dual
6 connect by level <= 26
7 )
8 SELECT substr(ename, 1, 1) AS init_name,
9 count(*) cnt
10 FROM emp
11 WHERE substr(ename, 1, 1) IN (SELECT letter from letters)
12 GROUP BY substr(ename, 1, 1)
13 UNION
14 SELECT l.letter AS init_name,
15 0 cnt
16 FROM letters l
17 WHERE l.letter NOT IN (SELECT substr(ename, 1, 1) FROM emp)
18 ORDER BY init_name
19 /
I CNT
- ----------
A 2
B 1
C 1
D 0
E 0
F 1
G 0
H 0
I 0
J 2
K 1
L 0
M 2
N 0
O 0
P 0
Q 0
R 0
S 2
T 1
U 0
V 0
W 1
X 0
Y 0
Z 0
26 rows selected.
SQL>
So, it gives the count of each letter of first name, and for the other letters which does not exist in the first name, the count is 0.

Generate the 26 letters using connect then left join to the first letter of the name and count them:
select letter, count(name) count
from (select chr(ascii('A')+level-1) letter from dual connect by level < 27) l
left join emp on substr(name, 1, 1) = letter
group by letter order by 1
See SQLFiddle
Attribution: My technique of generating letters uses elements of Lalit's answer.

Related

How to count or sum distinct values when there is a risk of intersection?

Imagine I have a table with people and their features:
group Name red_hair tall blue_eyes programmer
1 Mark 1 1 0 1
1 Sean 1 0 1 0
1 Lucas 1 1 1 1
2 Linda 0 1 1 1
I would like to count how many people of specific sets of features are in every group. In other words, I would like to make some bins without counting a person multiple times.
There are 2^4 (16) possible combinations of those sets, but I don't need so much.
For example, if a person has red_hair I don't care whether he or she has blue eyes or he or she a programmer. This person goes to the red hair bin of this group.
If a person is a programmer I don't care whether he or she is tall, but I don't want to count people who are already in a red hair bin. Because I have already counted them.
So I have a priority:
Red hair people counts first
Programmers second
People with blue eyes third
Expected result of this dataset:
group red_hair_persons programmers blue_eyes_persons
1 3 0 0
2 0 1 0
when I do this:
select group, count(case when red_hair = 1 then name end) as red_hair,
count(case when programmer = 1 and red_hair = 0 then name end) as programmers
from table
group by group
I fear that there would be some intersections. Or the logic with CASES would be so complex I could drown in it.
Am I right?
If so how could I avoid them? Maybe I am doing everything wrong and there is a better way to do what I want to. I have an enormous table with many features in it and I don't want to screw up.
Here's how I understood it:
SQL> with test (cgroup, name, red_hair, tall, blue_eyes, programmer) as
2 (select 1, 'mark' , 1, 1, 0, 1 from dual union all
3 select 1, 'sean' , 1, 0, 1, 0 from dual union all
4 select 1, 'lucas', 1, 1, 1, 1 from dual union all
5 select 2, 'linda', 0, 1, 1, 1 from dual
6 ),
7 priority as
8 (select t.*,
9 case when red_hair = 1 then 'A'
10 when programmer = 1 then 'B'
11 when blue_eyes = 1 then 'C'
12 else 'D'
13 end priority
14 from test t
15 )
16 select cgroup,
17 sum(case when priority = 'A' then 1 else 0 end) red_hair,
18 sum(case when priority = 'B' then 1 else 0 end) programmer,
19 sum(case when priority = 'C' then 1 else 0 end) blue_eyes,
20 sum(case when priority = 'D' then 1 else 0 end) other
21 from priority
22 group by cgroup;
CGROUP RED_HAIR PROGRAMMER BLUE_EYES OTHER
---------- ---------- ---------- ---------- ----------
1 3 0 0 0
2 0 1 0 0
SQL>
priority CTE puts every person into its priority group, based on their properties
the final select counts (using SUM + CASE) them per group
With a little bit of simple math involved in the conditional aggregation:
select "group",
sum("red_hair") red_hair_persons,
sum((1 - "red_hair") * "programmer") programmers,
sum((1 - "red_hair") * (1 - "programmer") * "blue_eyes") blue_eyes_persons
from tablename
group by "group"
See the demo.
Results:
> group | RED_HAIR_PERSONS | PROGRAMMERS | BLUE_EYES_PERSONS
> ----: | ---------------: | ----------: | ----------------:
> 1 | 3 | 0 | 0
> 2 | 0 | 1 | 0

Updating row, according to Rownum in Oracle

I have two tables in Oracle
TableProducts
Product_Code, and 20 others fields
BGU
LSO
MPA
MPA4
MPA5
TPA
UGU
For this example, now I have 7 values, but maybe 9 values later.
CREATE TABLE TableContacts AS SELECT *
FROM Contacts
WHERE Rownum <= (4*(SELECT Count(Distinct Product_Code) FROM TableProducts));
Now I have 28 Rows in my TableContacts.
Now I need To UPDATE the rows in order to create combinations test.
TableContacts
Product_Code, Email, PDF, and 17 others fields.
Email and PDF has two possible values 'N' or 'Y'.
I need to fill the TableContacts with the combinations of Product_Code, Email and PDF fields, according to Rownum position.
Rownum = 1 -> Product_Code='BGU', Email='N', PDF='N'
Rownum = 2 -> Product_Code='BGU', Email='N', PDF='Y'
Rownum = 3 -> Product_Code='BGU', Email='Y', PDF='N'
Rownum = 4 -> Product_Code='BGU', Email='Y', PDF='Y'
Rownum = 5 -> Product_Code='LSO', Email='N', PDF='N'
If I have 7 values for Product_Code, 2 by Email and 2 by PDF, then I will need to fill (7 * 2 *2) = 28 Rows.
How to create and SQL for this situation updating TableContacts?
Partially, requirement doesn't make sense. Rows in a table within the relational databases aren't sorted in any way, so - saying that you want to refer to a rownum is ... strange. That's why I modified the contacts table and added yet another column - rn - which shows that rownum of yours.
Also, this example shows only 3 products (didn't feel like typing all of them). Code that follows doesn't care about number of those products and will work the same regardless.
Products:
SQL> select * From products;
CODE
-----
BGU
LSO
MPA
Insert into Contacts:
SQL> insert into contacts (rn, code, email, pdf)
2 with temp as
3 (select p.code, x.lvl
4 from products p cross join (Select level lvl from dual connect by level <= 4) x
5 )
6 select t.lvl,
7 t.code,
8 case when t.lvl in (1, 2) then 'N'
9 when t.lvl in (3, 4) then 'Y'
10 end email,
11 --
12 case when t.lvl in (1, 3) then 'N'
13 when t.lvl in (2, 4) then 'Y'
14 end pdf
15 from temp t;
12 rows created.
Result:
SQL> select * From contacts
2 order by code, rn;
RN CODE E P
---------- ----- - -
1 BGU N N
2 BGU N Y
3 BGU Y N
4 BGU Y Y
1 LSO N N
2 LSO N Y
3 LSO Y N
4 LSO Y Y
1 MPA N N
2 MPA N Y
3 MPA Y N
4 MPA Y Y
12 rows selected.
SQL>
[EDIT: how to update table that contains rows?]
If I understood you correctly, this is what you initially have in the CONTACTS table:
SQL> select code, rownum from contacts;
CODE ROWNUM
----- ----------
BGU 1
LSO 2
MPA 3
BGU 4
LSO 5
MPA 6
BGU 7
LSO 8
MPA 9
BGU 10
LSO 11
MPA 12
12 rows selected.
SQL>
As I previously said: rownum is irrelevant here, it can change, you can't tell which rownum belongs to which code.
Anyway, such an update (merge, actually) does the job:
SQL> merge into contacts a
2 using (select c.code,
3 c.rowid,
4 row_number() over (partition by c.code order by null) rn
5 from contacts c
6 ) x
7 on (a.rowid = x.rowid)
8 when matched then update set
9 a.email = case when x.rn in (1, 2) then 'N'
10 when x.rn in (3, 4) then 'Y'
11 end,
12 a.pdf = case when x.rn in (1, 3) then 'N'
13 when x.rn in (2, 4) then 'Y'
14 end;
12 rows merged.
SQL> select * From contacts order by code, email, pdf;
CODE EMAIL PDF
----- ----- -----
BGU N N
BGU N Y
BGU Y N
BGU Y Y
LSO N N
LSO N Y
LSO Y N
LSO Y Y
MPA N N
MPA N Y
MPA Y N
MPA Y Y
12 rows selected.
SQL>

BigQuery: straight table format of matrix multiplication into more traditional Matrix multiplication format?

This question here shows how to get matrix multiplication into straight table format, for example given (6x1) (Path, value) matrix, you will get (36,1) straight table. Now I want to get the traditional matrix multiplication format, in the example it would be (6x6) matrix.
How to shape a straight table of matrix multiplication into more traditional matrix multiplication format?
--standardSQL
WITH MatrixA AS (
SELECT 1 AS p, 2 AS val UNION ALL
SELECT 2, -3 UNION ALL
SELECT 3, 4 UNION ALL
SELECT 4, -1 UNION ALL
SELECT 5, 0 UNION ALL
SELECT 6, 2
), MatrixB AS (
SELECT 1 AS p, -1 AS val UNION ALL
SELECT 2, 2 UNION ALL
SELECT 3, 3 UNION ALL
SELECT 4, 3 UNION ALL
SELECT 5, 0 UNION ALL
SELECT 6, 1
),
matrixMultiplication AS
(
SELECT a.p AS ap, b.p as bp, SUM(a.val * b.val) val
FROM MatrixA AS a
CROSS JOIN MatrixB AS b
GROUP BY a.p, b.p
ORDER BY a.p, b.p
)
--36 elements for the 6x6 PATHS Matrix
--TODO: how to shape it to 6x6 matrix?
SELECT * FROM matrixMultiplication
how to shape it to 6x6 matrix?
Below is for BigQuery Standard SQL. Few simple options
Option #1
#standardSQL
SELECT ap AS row, STRING_AGG(CAST(val AS STRING), ' ' ORDER BY bp) AS cols
FROM matrixMultiplication
GROUP BY row
-- ORDER BY row
when applied to dummy data from your question - result is
Row row cols
1 1 -2 4 6 6 0 2
2 2 3 -6 -9 -9 0 -3
3 3 -4 8 12 12 0 4
4 4 1 -2 -3 -3 0 -1
5 5 0 0 0 0 0 0
6 6 -2 4 6 6 0 2
Option #2
#standardSQL
SELECT row,
cols[OFFSET(0)] AS col1,
cols[OFFSET(1)] AS col2,
cols[OFFSET(2)] AS col3,
cols[OFFSET(3)] AS col4,
cols[OFFSET(4)] AS col5,
cols[OFFSET(5)] AS col6
FROM (
SELECT ap AS row, ARRAY_AGG(val ORDER BY bp) AS cols
FROM matrixMultiplication
GROUP BY ap
)
-- ORDER BY row
when applied to dummy data from your question - result is
Row row col1 col2 col3 col4 col5 col6
1 1 -2 4 6 6 0 2
2 2 3 -6 -9 -9 0 -3
3 3 -4 8 12 12 0 4
4 4 1 -2 -3 -3 0 -1
5 5 0 0 0 0 0 0
6 6 -2 4 6 6 0 2

Oracle - Assign count value for a column based on another column in select query

Consider, I have the following in a select query:
ID Flag
5 Y
5 Y
5 N
6 Y
6 Y
6 Y
6 N
I should be adding a new column count in the same select which counts the number of 'Y' records for the ID and assigns it to all. (Eg: ID=5 has 3 records. All of them should be assigned the count value as '2').
Output required in select query:
ID Flag count
5 Y 2
5 Y 2
5 N 2
6 Y 3
6 Y 3
6 Y 3
6 N 3
Use a window function:
select id,
flag,
count(case when flag = 'Y' then 1 end) over (partition by id) as "count"
from the_table
order by id;
The case expression will return null for flags with N and thus they will be ignored by the count() function

Find factorial in Oracle

I have a table which has a column call numbers
Numbers
------
3
5
I am trying to get the factorial of those. I am using the below logic but not with proper result
Select
Numbers
,EXP(SUM(LN(Numbers)) OVER (ORDER BY Numbers)) Factorial
FROM testTbl
*Output
*
Numbers Factorial
------ ---------
3 3.00000000000000000000000000000000000001
5 15.0000000000000000000000000000000000002
What is wrong? Please help
Expected
--------
Numbers Factorial
------ ---------
3 6
5 120
Thanks in advance
I've had a go at this from another angle, trying to do it all in a SQL statement (using your table testTbl and the column numbers).
This is what I've come up with, see if it suits you:
SELECT testtbl.numbers,
ROUND( EXP( SUM( LN( t1.n ) ) ) ) AS factorial
FROM ( SELECT UNIQUE LEVEL n
FROM testtbl
CONNECT BY LEVEL <= numbers) t1,
( SELECT UNIQUE LEVEL n
FROM testtbl
CONNECT BY LEVEL <= numbers) t2,
testTbl
WHERE t1.n <= t2.n
AND t2.n = testTbl.numbers
GROUP BY testtbl.numbers
ORDER BY testtbl.numbers;
Gives the output:
Numbers Factorial
3 6
5 120
Hope it helps...
Were it me, I'd create a factorial function and call that user-defined function in my query. Something like
SQL> create function factorial( p_n in number )
2 return number
3 is
4 begin
5 if( p_n = 1 )
6 then
7 return p_n;
8 else
9 return p_n * factorial( p_n - 1 );
10 end if;
11 end;
12 /
Function created.
SQL> with t as (
2 select 3 num from dual
3 union all
4 select 5 from dual
5 )
6 select num,
7 factorial(num)
8 from t;
NUM FACTORIAL(NUM)
---------- --------------
3 6
5 120
If for some reason you cannot define a new function and you really want to do it in SQL, you'll can generate all the numbers less than the number in your table and then aggregate those generated numbers.
SQL> ed
Wrote file afiedt.buf
1 with t as (
2 select 3 num from dual
3 union all
4 select 5 from dual
5 )
6 select t.num,
7 exp( sum(ln(gen.num))) factorial
8 from (select level num
9 from dual
10 connect by level <= (select max(t.num) from t)) gen,
11 t
12 where gen.num <= t.num
13* group by t.num
SQL> /
NUM FACTORIAL
---------- ----------
5 120
3 6

Resources