Auto Generate two new ID column based on other column Values in PostGreSQL database - sql

In my database table i have a table name Household member where the column are
Upzila, union , ward, village , para family_head_name , member_name ,
relation_with_family_head, age , maritial_status.
I want to generate a new table with same structure but with new auto-generate column the column name will be HH_ID , Member_id .Below i will provide simple dataset with the new example column of hh_id and hh_membe_id.
For example the Upazila is Cox Bazar Sadar so i will assume the code is 1 and the union is jhiwanja so jhionja code is 03 then if ward is number 1 and village is Boro chara so code is 01 and the para name is asroyon prokolo that code is 02 so the hh_id will be and the member id will be incremental for example if the house hold contain 3 people so for the first member id (hh_member_id) will be then second member id will be .
I have tried so many approch but i faild to generate that id . last time i have tried to generate the id using excel manually but i faild . so would be the best solution to do that in postgreSQL database .
Simple dataset link : https://docs.google.com/spreadsheets/d/1X33Zh2Yq_9Hz64VbW_u3lRi61-pKfQ5HozkylUsRVMU/edit?usp=sharing

Related

Issue with PIVOTING two columns at the same time and one includes a datetime column in SQL Server

I have a table used for attendance tracking, so I can track the arrival time of a person and the date in which they have arrived. I'm now trying to get a report based on that data and have created a view for it below. I have used the PIVOT function to split up the dates and it works without the column highlighted in bold below. The only issue is that I'm trying to PIVOT on a second column called DeviceFirstScannedTime which returns a datetime value, once that gets added the original PIVOT query doesn't group correctly.
Using SQL Server 2012
Current Query for PIVOTING
SELECT *
FROM (SELECT [Code] AS [CB Code], [Lastname], [Firstname], CompanyName AS [Company], DeviceScannedDateOnly, [Code], **DeviceFirstScannedTime**
FROM [dbo].[vLDN23_DailyReportForPivot]) AS SourceTable
PIVOT (Count([Code]) FOR DeviceScannedDateOnly IN ([06/02/2023], [07/02/2023])) AS PivotTable;
What it shows without the DeviceFirstScannedTime column added, shows it will pivot on DeviceScannedDateOnly and Split the dates correctly (it groups the two scans in the original source table and pivots them);
CB Code
Lastname
Firstname
Company
06/02/23
07/02/23
WSSPS24HX6
Smith
Bob
Stan
1
1
With the datetime column added I get the data separated;
CB Code
Lastname
Firstname
Company
DeviceFirstScannedTime
06/02/23
07/02/23
WSSPS24HX6
Smith
Bob
Stan
2023-02-06 10:12:0060
1
0
WSSPS24HX6
Smith
Bob
Stan
2023-02-07 13:87:0000
0
1
Data is now split which isn't ideal for reporting..
What I'm trying to do is this
Firstname
Company
06 Scanned time
06/02/23
07 Scanned Time
07/02/23
Bob
Stan
2023-02-06 10:12:0060
1
2023-02-07 13:87:0000
1
I've removed the first couple of columns to make it more readable but essentially I'm trying to PIVOT on two columns and split the table accordingly all into one line.
Is that possible with a datatime column?

CSV/XLXS into SQL Table : Best Way based on the format

I have the following case
I have the following csv file format example:
Year;Ligue1;Ligue2;Ligue3
2017;Manchester;Burnley;Doncaster
2016;Chelsea;Aston Villa;Leeds
2015;Arsenal;Newcastle;Sheffield
What I would like to create so far is a table/view with rows just for each year and each Ligue.
For instance : Year : 2017 ; Ligue : League 1 ; Team : Manchester
My idea is the following.
To bulk the CSV file into the database : Bulk into ...
Once the data is loaded I would iterate through all the records from first column (Ligue1 ) until the last column (Ligue 3) and insert these records into a specific view depending on the league classification.
For instance i will create the following view:
View Football with just 3 columns : Year , League, Winner
Insert into Football (Year, League = always the name of the Column (League 1, League 2 or League 3) Team ) where Team is the relevant Winner for the specific year.
Final Result Example:
Year;League;Winner
2017;League1;Manchester
2017;League2;Burnley
2017;League3;Doncaster
Would be the idea of bulking the CSV the best approach?
How could I get the results and cases described in the second step? With Counters / Cursors...?

show two different values in the same column-SSRS

I need to create a report(SSRS) ,but I can't figure out how i can get one specific value.
Please consider the following scenario: I Have a Hierarchy Country ->City->Person ,& i need to get the value of the wealth in one column for a specific person ,a specific city & a specific country.
the wealth of a counry is not the SUM of the wealth of the persons living in the country .
My report should look like :
USA : 20M$
NY: 3M$
Person1: 0,1M$
Person2: 0,2M$
Boston: 2M$
Person 3: 0,5M$
................
My query is :
;WITH wealth_TEMP AS
(
SELECT
fo.wealthId,
SUM(fo.wealth) AS wealth
FROM
(
SELECT
wealthId,
CASE
WHEN (Some Criteria)
THEN 1
ELSE 0
END AS wealth
FROM wealthTable f
) fo
GROUP BY wealthId
),
Hierarchy AS
(
SELECT
B.CityId AS CityId,
B.CountryName AS CountryName
FROM HierarchyTable AS B where
b.CountryName IN (#Country)
),
Person_Table AS
(
SELECT
fsu.individualId,
fsu.Cityid,
fo.welth
FROM Individual_Table FSU
LEFT OUTER JOIN wealth_TEMP fo ON fo.wealthId = fsu.individualId
WHERE bu.Cityname IN (#City)
)
Select ......................
Considering that your dataset returns something like it:
Country CountryWealth State StateWealth Person PersonWealth
USA 20M$ NY 3M$ Person 1 0,1M$
USA 20M$ NY 3M$ Person 2 0,2M$
USA 20M$ Boston 2M$ Person 3 0,5M$
Create a table with 5 columns and remove the header line
Insert tow new details line
In the first line and first column configure to the Country and Hide Duplicates to true
In the first line and second column configure to the CountryWealth and Hide Duplicates to true
In the second line and second column configure to the State and Hide Duplicates to true
In the second line and third column configure to the StateWealth and Hide Duplicates to true
In the third line and third to the end configure the others values
Order the table to Country, State, person
May, you need to add more columns and merge to get your desired lyout

One to many relationship on the same table

Here is the situation:-
I have a table called Users. This contains user data for students and tutors as most of the data required is the same.
Having completed the system I am now told that the client would like to be able to assign students to tutors.
Is there a legitimate/ clean way I can create a one to many relationship within a single table, perhaps via a link table?
I've tried to think this through but whatever solution I come up with seems messy.
I would be grateful for any input.
Thanks
Phill
Have you tried the following approach?
Make a new table, for example TutorStudent (choose a more appropriate name if needed). It should have two columns:
Tutor_ID
Student_ID
Both columns shall be the (composite) primary key, each column will be a foreign key to your Users table User_ID (I assume this is what you have).
So, if you have a tutor named Newton that has two students, Tesla and Edison, your Users table will have something like this:
User_ID, Name
1, Newton
2, Tesla
3, Edison
and your TutorStudent table will have following values:
Tutor_ID, Student_ID
1, 2
1, 3
Relatively simple and doesn't require any modifications to your existing table.
Do take care when deleting users - use the delete cascade feature of your database system or do some maintenance work afterwards so your TutorStudent table doesn't go stale when updating/removing your users.
My ideal for the same situation
Example: one book have many category:
Basic solution:
book table has recorded book information
category table has recored category information ex: 100 documents
book_category_relation table has single book (book_id) has category(category_id) 1 book may be have 100 category_id
Ideal solution:
First calculate total your category: ex 100 document. Each category equal value 1 bit: max 31 bit so 100 category we have ceil floor(100%31) = 4 groups
category_id = 1 : 1 (1%31) <=> 000000001 group 0 = floor(1/31)
category_id = 2 : 2 (2%31)<=> 000000010 group 0 = floor(2/31)
category_id = 3 : 4 (3%31)<=> 000000100 group 0 = floor(3/31)
category_id = 4 : 8(4%31)<=> 000001000 group 0 = floor(4/31)
...........................
category_id = 31: 2^31(31%31) <=>1000..000 group 0 if moduler 31 equal zero so number group = (31/31 -1)=0;
category_id = 32: 1(32%31) <=> 0000000001 group 1 = floor(32/31)
category_id = 33: 2(33%31) <=> 0000000010 group 1 = floor(33/31)
Ok now we add 4 fields in design book table (group_0,group_1,group_2,group_3) with int(11) unsigned and add index that fields
if book has category id = n so we can the following calculate formula:
bit code = (n%31 ==0)?31: (n%31)
number group field = (n%31==0)?(n/31 -1):floor(n/31)
ex: book in category_id = 100 so:
bit code = (100%31) =7 <=>2^7 = 128,
group = floor(100%31) = 3 <=> in group_3
so if you need query all book in category_id = 100, query string is:
SELECT * FROM book WHERE group_3&128
Note: MySQL not index working if bitwise in where.
But you can check in this link:
Bitwise operations and indexes

Fill a drop-down list parameter with specific available values

I have an SSRS report that creates report from a SQL table:
id type name
1 fruit wilk
2 fruit scot
3 paper jon
4 pen brad
5 tape lin
6 water james
The report has two data sets: one feeds query for report, and the other feeds data to parameter. So in the report the multi-value parameter gets its values from dataset2.
-- dataset1::
select ID, TYPE, name from table1 where type in (#types)
-- dataset2::
select TYPE from table1
The report is generated based on type selected from dropdown list (which is a multi select list).
For example if we select "fruit" the report displays:
wilk, scot
If we select "water":
james
Now the thing is that I need to create a name for all the values "TAPE", "pen", and "paper", say the name "STATIONARY", such that the dropdown list should show only:
fruit, stationary, water
And when I select "STATIONARY" from thedropdown list the report should display:
jon, brad, lin (all 3 have some form of stationary, i.e paper, pen, tape)
And when I select type as "STATIONARY" and "water" it should display:
jon, brad, lin, james
Just from the hip here.
Consider adding a category field to your table. So for your fruit and water you could have a category called "Food", and for your pen, paper, and tape the category would be called "stationary".
Add another dataset to your report called "category".
SELECT Category FROM table1
Add another parameter that is a multiple selection of your new data set called #Category.
In your main query add:
...AND Category IN (#Category)
EDIT
Keep in mind this advice completely ignores normalization in your database. I understand that is not the intent of your question but it is something you should always consider. If it were me I would even add a category table. Then with the "table1" as you call it I would add a foriegn key pointing at an ID in the category table. You can even see this issue with your type column. Notice how fruit is used more than once.
I'd create another couple of tables for this called Item and ItemType.
ItemType has two fields: ItemTypeId (the auto-incrementing primary key) and Name. ItemType will have values like:
ItemTypeId Name
1 Food
2 Stationery
Item has three fields: ItemId (the auto-incrementing primary key), Name and ItemTypeId (from the ItemType table above). It looks like this:
ItemId Name ItemTypeId
1 Fruit 1
2 Paper 2
3 Pen 2
4 Tape 2
5 Water 1
Add the ItemId field to table1 and remove the type field, so it now looks like:
id ItemId name
1 1 wilk
2 1 scot
3 2 jon
4 3 brad
5 4 lin
6 5 james
We now know the type of the item from the link to the ItemType.
Create two parameters: #ItemTypes and #Items as multi-value.
#ItemTypes populates from the ItemType table:
SELECT ItemTypeId, Name FROM ItemType
ItemTypeId is the Value and Name is the Label.
#Items populates from the Item table but is filtered on the #ItemTypes parameter like so:
SELECT ItemId, Name FROM Item WHERE (ItemTypeId IN #ItemTypes)
ItemId is the Value and Name is the Label.
Now when you select #ItemTypes in the first parameter, the second parameter will only show items of that type.
Okay, back to your query. Your main query now looks like:
SELECT Item.Name AS ItemName, ItemType.Name AS ItemTypeName, table1.Name
FROM table1
INNER JOIN Item ON Item.ItemId = table1.ItemId
INNER JOIN ItemType ON ItemType.ItemTypeId = Item.ItemTypeI
WHERE (ItemType.ItemTypeId IN #ItemTypes)
AND (Item.ItemId IN #Items)
and I think our work here is done.