Couting a Mysql Table - mysql

I have two Mysql tables which are:
1 - Main table (_benefits) which consists of benefitCode, benefitName and
2 - Second table which consists of clientID, benefitCode1, benefitCode2, etc.
what I need is that when I do a SELECT * FROM _benefits
I get a COUNT of all clients receiving the corresponding benefitCode
a small example would be:
Main Table
Benefit Code Benefit Name
6MBO 6 Monthly Bonus
AP Age Pension
Beneficiaries Table
clientID 6MBO AP
123M 1 0
456M 1 1
Required Output Select statement should give
Benefit Code Benefit Name Total
6MBO 6 Monthly Bonus 2
AP Age Pension 1
Thank you for your assistance

Related

MySQL iterate information from one table in to 2 columns in query

I have a database which holds maintenance reports for unique units that I need to pull information from in a single query. My issue is the convoluted way the information is stored.
SELECT date(reports.created_timestamp) as Date,
locations.name as Location,
location_groups.name as L_group,
units.name as Unit_name,
units.id as Unit_ID,
concat(users_2.first_name, "
",users_2.last_name) as Engineer,
reports.id as Report_ID
FROM reports
LEFT JOIN units
ON reports.unit_id = units.id
LEFT JOIN users_2
ON reports.user_id = users_2.id
LEFT JOIN locations
ON units.location_id = locations.id
LEFT JOIN location_groups
ON locations.locations_group_id = location_groups.id
where reports.created_timestamp >= '2022-01-01 00:00:00'
and locations.name NOT LIKE 'Company Vehicles'
and location_groups.name = 'Airports';
This returns:
Date
Location
L_group
Unit_name
Unit_ID
Engineer
Report_ID
2022-10-18
Airport 1
Airports
AIR-AAA1-N127
1
Engineer 1
19471
2022-10-19
Airport 2
Airports
AIR-BBB2-D03
4
Engineer 2
19486
2022-10-19
Airport 2
Airports
AIR-BBB2-D14
13
Engineer 2
19495
2022-10-25
Airport 2
Airports
AIR-BBB2-D13
14
Engineer 2
19518
However, when the engineers are completing maintenance they have to do several tasks depending on the "unit" type. This is held in the units table as unit_type_id variable. This then references display_type_report_tasks to determine what tasks should be completed based on the unit_type_id, e.g:
id
unit_type_id
report_task_id
1
3
1
2
13
1
9
13
2
3
14
1
4
15
1
The report_task_id's then relate to table report_tasks which holds the following as an example:
id
name
text
description
1
Unit Cleaned-Internal
Unit Cleaned-Internal
Unit Cleaned-Internal
2
Unit Cleaned-External
Unit Cleaned-External
Unit Cleaned-External
3
Bumper Bar Fixed
Bumper Bar Fixed
Bumper Bar Fixed
4
Tile Replaced
Tile Replaced
Tile Replaced
5
Hardware Replaced
Hardware Replaced
Hardware Replaced
Picking unit type 13 as an example, when an engineer completes a report, the task options are stored in reports_tasks_selected_options such as the following:
id
report_tasks_option_id
example_report_id
30452
1
19558
30453
9
19558
The report_tasks_option_id then relates to report_tasks_options:
id
value
description
report_task_id
1
1
Not cleaned
1
2
2
Internal Clean
1
3
3
Deep Clean
1
7
1
Not cleaned
2
8
2
External Clean
2
9
3
Deep Clean
2
I want to query the unit_type_id and dynamically assign the column headers using report_tasks.name depending on what unit types are returned. (If a unit is returned that doesn't utilise all columns then NULL is used where no result is returned.)
I have to build reports per unit_type and statically assign the columns, BUT I cannot figure out how to then iterate through reports_tasks_selected_options to get the report_tasks_options.description for the results. As an example (using report_id = 19558) my current query output would be:
Date
Location
L_group
Unit_name
Unit_ID
Engineer
2022-11-01
Airport 3
Airports
AIR-CCC1-D09
1907
Engineer 3
But because I know this is unit_type=13 I know that the report_tasks related to it are Unit Cleaned-Internal and Unit Cleaned-External. So I want to iterate through the reports_tasks_selected_options table for that report number (As I know that the lower ID is always Unit Cleaned-Internal because it has the lower ID in report_tasks, and so the higher ID from reports_tasks_selected_options is always going to be Unit Cleaned-External.)
Desired output:
Date
Location
L_group
Unit_name
Unit_ID
Engineer
Report_ID
Clean-Int
Clean-Ext
2022-11-01
Airport 3
Airports
AIR-CCC1-D09
1907
Engineer 3
19558
Not cleaned (1)
Deep Clean (9)
I put the option numbers in brackets for clarity but do not require them in my output.

Find next occurrence from a reference table sql

I have searched many other questions, but cant find a usable comparison. I have a SQL table that has a list of all the rooms at our hotel. I want to know the next time each room is going to be occupied. There are two tables I am looking at, one contains the name and details of each room we have, for all intents it is a static table. The other table is a reservations table that shows check in and check out times, and has a column that references which room is being used.
Table Rooms
unique id name
1 Room 3
2 Room 4
3 Suite 1
4 Suite 2
5 Suite 3
Table Reservations
unique id start date room id
1 12/4/16 3
2 12/4/16 4
3 12/6/16 3
4 12/12/16 3
5 12/14/16 2
6 12/20/16 2
This would return only 3 values:
2 12/20/16
3 12/4/16
4 12/4/16
If also possible I would like the make it so that if a reservation is not found a null value is returned, so ultimately, the return value would be
Room Next Occurrence
1 null
2 12/20/16
3 12/4/16
4 12/4/16
5 null
Is there a way of doing this without my current php hack that runs 200 sql queries?
Thanks so much!
You can use left join
select rooms.id, rooms.name, reservations.`start date`
from Rooms
left join reservations on reservations.`room id` = Rooms.id
order by rooms.id

T-SQL query procedure-insert

I am wondering if any of you would be able to help me. I am trying to loop through table 1 (which has duplicate values of the plant codes) and based on the unique plant codes, create a new record for the two other tables. For each unique Plant code I want to create a new row in the other two tables and regarding the non unique PtypeID I link any one of the PTypeID's for all inserts it doesnt matter which I choose and for the rest of the fields like name etc. I would like to set those myself, I am just stuck on the logic of how to insert based on looping through a certain table and adding to another. So here is the data:
Table 1
PlantCode PlantID PTypeID
MEX 1 10
USA 2 11
USA 2 12
AUS 3 13
CHL 4 14
Table 2
PTypeID PtypeName PRID
123 Supplier 1
23 General 2
45 Customer 3
90 Broker 4
90 Broker 5
Table 3
PCreatedDate PRID PRName
2005-03-21 14:44:27.157 1 Classification
2005-03-29 00:00:00.000 2 Follow Up
2005-04-13 09:27:17.720 3 Step 1
2005-04-13 10:31:37.680 4 Step 2
2005-04-13 10:32:17.663 5 General Process
Any help at all would be greatly appreciated
I'm unclear on what relationship there is between Table 1 and either of the other two, so this is going to be a bit general.
First, there are two options and both require a select statement to get the unique values of PlantCode out of table1, along with one of the PTypeId's associated with it, so let's do that:
select PlantCode, min(PTypeId)
from table1
group by PlantCode;
This gets the lowest valued PTypeId associated with the PlantCode. You could use max(PTypeId) instead which gets the highest value if you wanted: for 'USA' min will give you 11 and max will give you 12.
Having selected that data you can either write some code (C#, C++, java, whatever) to read through the results row by row and insert new data into table2 and table3. I'm not going to show that, but I'll show how the do it using pure SQL.
insert into table2 (PTypeId, PTypeName, PRID)
select PTypeId, 'YourChoiceOfName', 24 -- set PRID to 24 for all
from
(
select PlantCode, min(PTypeId) as PTypeId
from table1
group by PlantCode
) x;
and follow that with a similar insert.... select... for table3.
Hope that helps.

SQL query for multiple (one-to-many) tables in mysql database

I have a database with tours (group city tours with guide). What I need is a SQL query (for a mysql 5.1.54 database) that will eventually give me a PHP array with the information out of multiple tables combined. I'm able to accomplish this by doing a query just for the first 3 tables and then adding the information in table 4 and 5 within a foreach loop.
But, I need to use the query for searching/filtering (like: show all reservations where partner has id 9) so I need SQL to select the corresponding reservations.
Reservations with no partners (table 4) and/or guides (table 5) must be included.
All partners and guides must be included in the result (reservation can have more partners/guides)
All information in table 4 and 5 must be included (like the status from table 4).
A simplified version of the database:
Table 1: reservations:
id id_client id_tour
1 22 6
2 23 5
Table 2: clients (one reservation has one client):
id name
22 John
23 William
Table 3: tours (one reservation has one tour)
id name
5 big tour
6 small tour
Table 4: partners (one reservation can have multiple partners):
id id_reservation id_partner_type id_partner status
34 1 9 16 1
35 1 9 17 0
Table 5: guides (one reservation can have multiple guides):
id id_reservation id_guide
18 1 14
19 1 15
I have tried to work this out but I just can not get a query that does the job. I used GROUP_CONCAT to get the multiple partner and guide id's. Biggest problem I have is not being able to include the reservations that have no partners and/or guides like reservation 2.
To include all reservations that have no partners and guides you need to use OUTER JOINs, for example the following query will gives you all information from your tables 4, 5 including your condition:
Select p.*, g.*
from reservations r
left outer join partners p on p.id_reservation = r.id
left outer join guides g on g.id_reservation = r.id
where p.id_reservation is null and g.id_reservation is null

MS Access 2007 Rows to columns in recordset

I have a table which is like a questionnaire type ..
My original table contains 450 columns and 212 rows.
Slno is the person's id who answer the questionaire .
SlNo Q1a Q1b Q2a Q2b Q2c Q2d Q2e Q2f .... Q37c <450 columns>
1 1
2 1 1
3 1
4 1 1
5 1
I have to do analysis for this data , eg Number of persons who is male (Q1a) and who owns a boat (Q2b) i.e ( select * from Questionnaire where Q1a=1 and Q2b=1 ).. etc .. many more combinations are there ..
I have designed in MS access all the design worked perfectly except for a major problem ( Number of table columns is restricted to 255 ).
To be able to enter this into access table i have inserted in as 450 rows and 212 columns (now am able to enter this into access db). Now while fetching the records i want the record set to transpose the results into the form that i wanted so that i do not have to change my algorithm or logic .... How to achieve this with the minimum changes ? This is my first time working with Access Database
You might be able to use a crosstab query to generate what you are expecting. You could also build a transpose function.
Either way, I think you'll stil run into the 255 column limit and MS Access is using temporary table, etc.
However, I think you'll have far less work and better results if you change the structure of your table.
I assume that this like a fill-in-the-bubble questionnaire, and it's mostly multiple choice. In which case instead of recording the result, I would record the answer for the question
SlNo Q1 Q2
1 B
2 B
3 A
4 A C
5 A
Then you have far fewer columns to work with. And you query for where Q1='A' instead of Q1a=1.
The alternative is break the table up into sections (personal, career, etc.) and then do a join, and only show the column you need (so as not to exceed that 255 column limit).
An way to do this that handles more questions is have a table for the person, a table for the question, and a table for the response
Person
SlNo PostalCode
1 90210
2 H0H 0H0
3
Questions
QID, QTitle, QDesc
1 Q1a Gender Male
2 Q1b Gender Female
3 Q2a Boat
4 Q2b Car
Answers
SlNo QID Result
1 2 True
1 3 True
1 4 True
2 1 True
2 3 False
2 4 True
You can then find the question takers by selecting Persons from a list of Answers
select * from Person
where SlNo in (
select SlNo from Answers, Questions
where
questions.qid = answers=qid
and
qtitle = 'Q1a'
and
answers.result='True')
and SlNo in (
select SlNo from Answers, Questions
where
questions.qid = answers=qid
and
qtitle = 'Q2a'
and
answers.result='True')
I finally got the solutions
I created two table one having 225 columns and the other having 225 column
(total 450 columns)
I created a SQL statement
select count(*) from T1,T2 WHERE T1.SlNo=T2.SlNo
and added the conditions what i want
It is coming correct after this ..
The database was entered wrongly by the other staff in the beginning but just to throw away one week of work was not good , so had to stick to this design ... and the deadly is next week .. now it's working :) :)