How to make summary table of with respect to data in tables in access - sql

This site is really good and I have got many help from u all.. So thank u for your help.
Now I have doubt. I have 3 tables called b1,b2,b3 in access having the same field but different data.
I want to make summary of the data in it in single table, like in b1 there is cable1 with 4m length, and in b3 there is cable1 with 8 m length..so in summary it should show cable 1 with 8+4 m length.
Any idea how to do it? Does union query help in this situation?

Purely based on your descriptioin and with no detail of your tables I would assume you are looking for something like this:
SELECT [CableType],
convert(nvarchar(5),B1.[Length]) + 'm +' + convert(nvarchar(5),B2.[Length])
+ 'm +' + convert(nvarchar(5),B3.[Length]) + 'm' as [Length]
FROM [B1]
join [B2] on [B1].[ID] = [B2].[ID]
join [B3] on [B1].[ID] = [B3].[ID]
I guess you have a column which holds the "Cable 1" description somewhere, also assuming you have an identifying column of some kind and your Lengths are stored as a number of some kind. This example would assume you always populate all 3 tables.

Related

Defaulting missing data

I have a complex set of schema that I am trying to pull data out of for a report. The query for it joins a bunch of tables together and I am specifically looking to pull a subset of data where everything for it might be null. The original relations for the tables look as such.
Location.DeptFK
Dept.PK
Section.DeptFK
Subsection.SectionFK
Question.SubsectionFK
Answer.QuestionFK, SubmissionFK
Submission.PK, LocationFK
From here my problems begin to compound a little.
SELECT Section.StepNumber + '-' + Question.QuestionNumber AS QuestionNumberVar,
Question.Question,
Subsection.Name AS Subsection,
Section.Name AS Section,
SUM(CASE WHEN (Answer.Answer = 0) THEN 1 ELSE 0 END) AS NA,
SUM(CASE WHEN (Answer.Answer = 1) THEN 1 ELSE 0 END) AS AnsNo,
SUM(CASE WHEN (Answer.Answer = 2) THEN 1 ELSE 0 END) AS AnsYes,
(select count(distinct Location.Abbreviation) from Department inner join Plant on location.DepartmentFK = Department.PK WHERE(Department.Name = 'insertParameter'))
as total
FROM Department inner join
section on Department.PK = section.DepartmentFK inner JOIN
subsection on Subsection.SectionFK = Section.PK INNER JOIN
question on Question.SubsectionFK = Subsection.PK INNER JOIN
Answer on Answer.QuestionFK = question.PK inner JOIN
Submission on Submission.PK = Answer.SubmissionFK inner join
Location on Location.DepartmentFK = Department.PK AND Location.pk = Submission.PlantFK
WHERE (Department.Name = 'InsertParameter') AND (Submission.MonthTested = '1/1/2017')
GROUP BY Question.Question, QuestionNumberVar, Subsection.Name, Section.Name, Section.StepNumber
ORDER BY QuestionNumberVar;
There are 15 total locations, with this query I get 12. If I remove a relation in the join for Location I get 15 total locations but my answer data gets multiplied by 15. My issue is that not all locations are required to test at the same time so their answers should default to NA, They don't get records placed in the DB so the relationship between Location/Submission is absent.
I have a workaround almost in place via the select count distinct but, The second part is a query for finding what each location answered instead of a sum which brings the problem right back around. It also has to be dynamic because the input parameters for a department won't bring a static number of locations back each time.
I am still learning my SQL so any additional material to look at for building this query would also be appreciated. So I guess the big question here is, How would I go about creating default data in this query for anytime the Location/Submission relation has a null value?
Edit: Dummy Data
QuestionNumberVar | Section | Subsection | Question | AnsYes | AnsNo | NA (expected)
1-1.1 Math Algebra Did you do your homework? 10 1 1(4)
1-1.2 Math Algebra Did your dog eat it? 9 3 0(3)
2-1.1 English Greek Did you do your homework? 8 0 4(7)
I have tried making left joins at various applicable portions of the code to no avail. All attempts at left joins have ended with no effect on info output. This query feeds into the Dataset for an SSRS report. There are a couple workarounds for this particular section via an expression to take total Locations and subtract AnsYes and AnsNo to get the true NA value but as explained above doesn't help with my next query.
Edit: SQL Server 2012 for those who asked
Edit: my attempt at an isnull() on the missing data returns nothing I suspect because the query already eliminates the "null/missing" data. Left joining while doing this has also failed. The point of failure is on Submissions. if we bind it to Locations there are locations missing but if we don't bind it there are multiplied duplicates because Department has a One-To-Many with Location and not vice versa. I am unable to make any schema changes to improve this process.
There is a previous report that I am trying to emulate/update. It used C# logic to process data and run multiple queries to attain the same data. I don't have this luxury. (previous report exports to excel directly instead of SSRS). Here is the previous logic used.
select PK from Department where Name = 'InsertParameter';
select PK from Submission where LocationFK = 'Location.PK_var' and MonthTested = '1/1/2017'
Then it runs those into a loop where it processes nulls into NA using C# logic
EDIT (Mediocre Solution): I ended up doing the workaround of making a calculated field that subtracts Yes and No from the total # of Locations that have that Dept. This is a mediocre solution because I didn't solve my original problem and made 3 datasets that should have been displayed as a singular dataset. One for question info, one for each locations answer and one for locations that didnt participate. If a true answer comes up I will check its validity but for now, Problem psuedo solved.

Joining SQL statements Atrium Syntess Firebird DB

I'm trying to get (one or multiple) number lines (PROGCODE) that are attached to an OBJECT (i.e. a building) that is connected to a Relation which in turn has a GC_ID (relation unique ID). I need all the buildings & progcodes connected to a relation ID in a firebird 2.5 database generated by my companies ERP system.
I can look through all the tables in the firebird database and run select queries on them.I like to think I have the join statement syntax down and I know how to find the unique ID belonging to a relation, unfortunately I'm unsure how I can find the correct table that houses the information I seek.
The table I think this data is in has the following fields:
GC_ID, DEVICE_GC_ID, USER_GC_ID, CODE, DESCRIPTION.
However when I query it using
select GC_ID, DEVICE_GC_ID, USER_GC_ID, CODE, DESCRIPTION
from AT_PROGCODE A
Then I get a description of the fields I'm trying to query.
i.e.
| GC_ ID : 100005 | DEVICE_GC_ID : 100174 | USER_GC_ID : 1000073 | DESCRIPTION: >description of what I'm trying to query< |
Can anyone shed some insight how I should handle this?
Update 7-09-2017
I spoke with the ERP consultant and was told the tables I needed (if anyone reading this is using syntess Atrium; the AT_BRENT table holds a description of all the tables.)
However, I've run into a new problem; the data I get from my sql query keeps streaming (it seems to never end with me stopping the script at 90 mil loops and the ERP program crashing if I ask for a count).
select A.GC_OMSCHRIJVING Bedrijf, A.GC_CODE ,M.GC_OMSCHRIJVING Werktitel,
M.TELEFOON1, M.TELEFOON2, M.MOBIEL, M.EMAIL,
M.URL, M.DOORKIES_NR, M.WERKLOCATIE, M.EMAIL_INTERN
from AT_MEDEW M , AT_RELATIE A
JOIN AT_MEDEW ON A.GC_ID = M.GC_ID
WHERE M.TELEFOON1 <> '' OR M.TELEFOON2 <> '' OR M.MOBIEL <> ''
Any ideas on what's the cause for my latest peril?
First I had to find the AT_BRENT table which holds all the descriptions for tables in Syntess Atrium
Then I was using a CROSS JOIN (as pointed out by https://stackoverflow.com/users/696808/bacon-bits )
I ended up using
select A.GC_OMSCHRIJVING Bedrijf, A.GC_CODE ,M.GC_OMSCHRIJVING Werktitel,
M.TELEFOON1, M.TELEFOON2, M.MOBIEL, M.EMAIL,
M.URL, M.DOORKIES_NR, M.WERKLOCATIE, M.EMAIL_INTERN
from AT_MEDEW M
JOIN AT_RELATIE A ON A.GC_ID = M.GC_ID
WHERE M.TELEFOON1 <> '' OR M.TELEFOON2 <> '' OR M.MOBIEL <> ''
Thank you all who helped.

Best Table Structure Design for Dynamic SQL statement

I am looking for the best table structure to create a dynamic SQL statement like this below (which is not dynamic yet). I have to choose between
joined tables
a single row with all columns with the content comma-delimted which I then will parse
one large table with multiple rows per Cost Centre Activity Code
or anything else
In this example the key which all link to is: 'NSEA8102' which is a Cost Centre Activity code
SELECT
#pDate,
#pDate,
'NSEA8102', --Cost Centre Activity Code
ccg.tCCGroup,
SUM(logs.tTripHours) AS tTriphours,
'Actual EMV Hours Worked - ' + DATENAME(MONTH,#pDATE) + ' ' + CAST(YEAR(#pDate) AS CHAR(4))
FROM dbo.tblEMV_Logsheet AS logs INNER JOIN
dbo.tblLookup_EMVEquipment AS ccg ON logs.tEquipmentKey = ccg.tEquipmentKey
WHERE tDate BETWEEN #BMonth and #EMonth
AND (logs.tAreaCode in ('MINEE', 'SERVICE'))
AND (logs.tEventCode LIKE 'RASSTEEPS')
AND logs.tSourceLocationCode = 'STEEPS'
AND logs.tDestinationLocationCode = 'ERASSTSP'
AND (ccg.tCCGroup IN ('FADT', 'FPC800', 'FWA800'))
AND ccg.tValid = 1
GROUP BY ccg.tCCGroup
Any suggestion would be welcome. Thanks

SQL - Getting a column from another table to join this query

I've got the code below which displays the location_id and total number of antisocial crimes but I would like to get the location_name from a different table called location_dim be output as well. I tried to find a way to UNION it but couldn't get it to work. Any ideas?
SELECT fk5_location_id , COUNT(fk3_crime_id) as TOTAL_ANTISOCIAL_CRIMES
from CRIME_FACT
WHERE fk1_time_id = 3 AND fk3_crime_id = 1
GROUP BY fk5_location_id;
You want to use join to lookup the location name. The query would probably look like this:
SELECT ld.location_name, COUNT(cf.fk3_crime_id) as TOTAL_ANTISOCIAL_CRIMES
from CRIME_FACT cf join
LOCATION_DIM ld
on cf.fk5_location_id = ld.location_id
WHERE cf.fk1_time_id = 3 AND cf.fk3_crime_id = 1
GROUP BY ld.location_name;
You need to put in the right column names for ld.location_name and ld.location_id.
you need to find a relationship between the two tables to link a location to crime. that way you could use a "join" and select the fields from each table you are interested in.
I suggest taking a step back and reading up on the fundamentals of relational databases. There are many good books out there which is the perfect place to start.

SQL Table Joins - What am I doing wrong?

I'm in a intro to database class, and one of my queries is seriously giving me trouble.
The assignment says to: Write a query to display the Passenger name, Seat No and Destination. Display this in one column title Travellers_info. This column should display data in the following format “ Mary Ann Jenkins is assigned to Seat 15 on the way to Bellmead”
This is the relationship view: http://prntscr.com/1jsoay
Can somebody please help me out, I'm not sure where I've gone wrong.
SELECT passenger.name + 'is assigned to Seat'
+ seat_info.seat_no + 'on the way to'
+ departure_info.destination AS Travellers_info
FROM passenger, seat_info, departure_info, seat_passenger, manages
WHERE passenger.Pass_id=seat_passenger.pass_id
AND seat_passenger.Seat_id=seat_info.Seat_id
AND seat_info.seat_id=manages.Seat_id
AND manages.Dept_id=departure_info.dept_id
You cant "add" text values using the "+" operator.
Without knowing which database you are using, the solution is probably either using CONCAT():
SELECT concat(passenger.name, 'is assigned to Seat', seat_info.seat_no,
'on the way to', departure_info.destination) AS Travellers_info
FROM passenger, seat_info, departure_info, seat_passenger, manages
WHERE passenger.Pass_id=seat_passenger.pass_id
AND seat_passenger.Seat_id=seat_info.Seat_id
AND seat_info.seat_id=manages.Seat_id
AND manages.Dept_id=departure_info.dept_id
or using the || operator:
SELECT passenger.name || 'is assigned to Seat'
|| seat_info.seat_no || 'on the way to'
|| departure_info.destination AS Travellers_info
FROM passenger, seat_info, departure_info, seat_passenger, manages
WHERE passenger.Pass_id=seat_passenger.pass_id
AND seat_passenger.Seat_id=seat_info.Seat_id
AND seat_info.seat_id=manages.Seat_id
AND manages.Dept_id=departure_info.dept_id
Have you tried double-checking all your tables (especially the joining tables like "manages" and "seat_passenger") to make sure you have valid data in them that would appropriately join up?
Also, make sure you have spaces in your text.
e.g.: 'is assigned to Seat' should be ' is assigned to Seat '
If you are getting no data it must be in your join criteria. Reduce your select to just a column from your first table and then join each table one at a time and see when it is that you stop getting data back
First off, you're going to want to put a space before is so that it won't look mushed together.
passenger.name + ' is assigned to seat'
Typically, you use subqueries and left outer joins for something of this sort. You do not just want to pull out all the data at once from all those tables. Let me see if I can explain this with some SQL. If you don't understand my example, go here: http://thenewboston.org/watch.php?cat=49&number=20 and watch 20-23 and you'll for sure understand it.
SELECT c.name + ' is assigned to Seat ' + c.seat_no + ' on the way to ' + departure_info.destination as Travellers_info
FROM departure_info
LEFT OUTER JOIN (SELECT b.Pass_id, b.name, b.seat_id, b.seat_no
FROM seat_no
LEFT OUTER JOIN (SELECT a.Pass_id, a.name, seat_passenger.seat_id
FROM seat_passenger
LEFT OUTER JOIN (SELECT passenger.name, passenger.Pass_id
from passenger
LEFT OUTER JOIN
ON passenger.Pass_id = seat_passenger.Pass_id) a seat_info
ON a.seat_id = seat_info.seat_id) b manages
ON b.seat_id = manages.seat_id) c departure_info
ON c.Dept_id = departure_info.Dept_id
I do not believe this will yield you the correct answer. But, it will get you working towards the right answer. I think I made a mistake after the third subquery. Remember that SQL evaluates things from the inside, then goes out. Just keep that in mind. Hope this helps.
try this in MSSQL or MSAccess.
for query optimization use ON (Join)
SELECT passenger.name + 'is assigned to Seat '
+ ltrim(rtrim(convert(char,seat_info.seat_no))) + ' on the way to'
+ departure_info.destination AS Travellers_info
FROM passenger p
join seat_passenger sp on sp.pass_id = p.Pass_id
join seat_info s on s.Seat_id = sp.Seat_id
join manages m on m.Seat_id = s.Seat_id
join departure_info d on d.dept_id = m.dept_id
concat in 2008R2 is not a valid function so you need to convert a number data to character.
while in 2012 it is available.