Select in select statement (Join Table) SQL - sql-server-2008

What select statement I should use to get the result as below:
Currently when i run my stored procedure below, it will display the "Result" image:
select vm.ID_Vendor,vm.Vendor_Name,vpe.Company_Name,vpe.TOTAL,
vpe.COUNT,vpe.AVERAGE from VENDOR_MASTER vm
LEFT JOIN
(select vvd.ID_Vendor,sc.ID_Company,sc.Company_Name,vvd.VPE_Average_Score,
SUM(vvd.VPE_Average_Score) AS TOTAL,COUNT(vvd.VPE_Total_Score) AS COUNT,
(SUM(vvd.VPE_Average_Score)/COUNT(vvd.VPE_Total_Score)) AS AVERAGE,
vvm.Assessor_Name FROM VENDOR_VPE_MASTER vvm
left join VENDOR_VPE_DETAIL vvd on vvm.ID_VPE_Master=vvd.ID_VPE_Master
left join SETUP_COMPANY sc on vvm.ID_Company=sc.ID_Company
left join REF_EVL_RATING rer1 on vvd.Quality_Product=rer1.ID_Evl_Rating
left join REF_EVL_RATING rer2 on vvd.Service=rer2.ID_Evl_Rating
left join REF_EVL_RATING rer3 on vvd.Technical=rer3.ID_Evl_Rating
left join REF_EVL_RATING rer4 on vvd.Quality_Mgmt=rer4.ID_Evl_Rating
left join REF_EVL_RATING rer5 on vvd.Price=rer5.ID_Evl_Rating
GROUP BY vvd.ID_Vendor,sc.ID_Company,sc.Company_Name,vvd.VPE_Average_Score,
vvd.VPE_Average_Score,vvd.VPE_Total_Score,vvm.Assessor_Name) as vpe on vm.ID_Vendor=vpe.ID_Vendor
order by vpe.ID_Vendor

EDIT: It seems now that you want to change your GROUP By clause, see my comment below
This is not possible as the SQL Server Management Studio is about the data and server management, it's not made to create reports or export well-formatted data (as said in the comments). However, if you have Excel installed, you can execute the query from Excel (Data -> Get External Data). This allows you to format the headers as you want and it is easier to export to other formats (PDF, images, ...).
As an alternative, you could use Reporting Services where you have a lot of possibilities for these things. However, the Excel solution will be easier to implement if you only need vertical headers.

Related

Mysql - same query different results

I am creating a report in Crystal and the report is consistently wrong and we tracked it back to the results being returned from the server.
Environment is MySQL 5.6.19 + MySQL ODBC 5.3.6.
Tables are InnoDB.
The query that Crystal is generating is:
SELECT `Encounter`.`Id`, `Transact`.`Client_No`, `Transact`.`Amount`,
`Transact`.`Process_Date`, `Codelist`.`Type`, `Encounter`.`Co_Res`,
`Codelist`.`ProcType`, `Transact`.`Id`, `Client`.`Name`,
`Transact`.`Patient_No`, `Transact`.`Encounter_No`, `Transact`.`Quantity`,
`Encounter`.`Date_Of_Service`, `Encounter`.`Status`,
`Insuranceschedule`.`Ins1Order`, `Insuranceschedule`.`Ins2Order`,
`Insuranceschedule`.`Ins3Order`, `Insuranceschedule`.`Ins4Order`,
`Insuranceschedule`.`Ins5Order`, `Insuranceschedule`.`Ins6Order`,
`Ins1`.`Plan_Type`, `Ins2`.`Plan_Type`, `Ins5`.`Plan_Type`,
`Encounter`.`No`, `Ins3`.`Plan_Type`, `Ins4`.`Plan_Type`,
`Ins6`.`Plan_Type`
FROM {oj (((((((((`Production`.`transact` `Transact`
INNER JOIN `Production`.`client` `Client`
ON `Transact`.`Client_No`=`Client`.`Client_No`)
INNER JOIN `Production`.`codelist` `Codelist`
ON `Transact`.`Code`=`Codelist`.`Code`)
INNER JOIN `Production`.`Encounter` `Encounter`
ON (`Transact`.`Patient_No`=`Encounter`.`Patient_No`)
AND (`Transact`.`Encounter_No`=`Encounter`.`No`))
LEFT OUTER JOIN `Production`.`insuranceschedule` `Insuranceschedule`
ON `Encounter`.`InsuranceRecord`=`Insuranceschedule`.`Insurance_Id`)
LEFT OUTER JOIN `Production`.`Insco` `Ins1`
ON `Insuranceschedule`.`Ins1`=`Ins1`.`No`)
LEFT OUTER JOIN `Production`.`Insco` `Ins2`
ON `Insuranceschedule`.`Ins2`=`Ins2`.`No`)
LEFT OUTER JOIN `Production`.`Insco` `Ins3`
ON `Insuranceschedule`.`Ins3`=`Ins3`.`No`)
LEFT OUTER JOIN `Production`.`Insco` `Ins4`
ON `Insuranceschedule`.`Ins4`=`Ins4`.`No`)
LEFT OUTER JOIN `Production`.`Insco` `Ins5`
ON `Insuranceschedule`.`Ins5`=`Ins5`.`No`)
LEFT OUTER JOIN `Production`.`Insco` `Ins6`
ON `Insuranceschedule`.`Ins6`=`Ins6`.`No`}
WHERE (`Transact`.`Process_Date`>={d '2016-01-01'}
AND `Transact`.`Process_Date`<={d '2016-12-31'})
AND `Transact`.`Client_No`=763 ORDER BY `Encounter`.`No`;
So far we cannot understand why this result is different almost every time it's run.
First time we might get 57,868 records
Second time.... 30,102
Third time 77,875
and so forth...
At least 1 out of 10 times it does produce the correct result.
We have:
- Dumped the tables and reloaded them.
- Checked collation on the tables.
- Tried a different physical server with a clean import of the data.
- Tried with and without ordering the results
- Looked for anything amiss with EXPLAIN - which is always the same every time it's run.
But this query is consistently inconsistent and we can't spot the problem. We are running this query on the commandline so it can't be Crystal or ODBC - unless the query it's creating is wrong?
Thanks in advance for looking at this!

Retrieving uniq records with union in mysql

I have two tables usersin and usersout(I can not change schema, a lot of system changes must be done in php otherwise). I should get all user records in a query but I should mark them if they are in or out also a user may have an in record and out record I shouldn't show in record if has an out record.
I have created tables with sample data in SQL Fiddle: http://www.sqlfiddle.com/#!9/ac99a/1/0
Can u help me how can I remove duplicates of user records in this union query?
If you want to have all entries with an entry in either the in or out table, but not in both of them, then a full outer join would be your friend.
Since MySQL does not know that kind of join, you can emulate it with a left outer join and a right outer join combined like so:
SELECT
ui.id, ui.user, 'i'
FROM
usersIN ui
LEFT OUTER JOIN
usersOUT uo ON ui.user = uo.user
WHERE uo.id IS NULL
UNION
SELECT
uo.id, uo.user, 'o'
FROM
usersIN ui
RIGHT OUTER JOIN
usersOUT uo ON ui.user = uo.user
WHERE ui.id IS NULL;
This should give you the right output.
A good visual explanation of joins can be found here

Need SQL aid for query with LEFT JOIN

I'm a beginner in sql and need some help using the left join (or alternate) function inthe following:
I have 2 tables:
1) Client
2) Server
Client has 2 columns (country and clientname) which is not present in Server. I want to join / copy these two columns into the Server table using the unique identifier column 'ClientID' present in both tables to match and join. How would I go about doing this and does anything recommend an easier way? I currently don't have physical access to a DB so I can't really test out any queries, so any help is appreciated!
Thank you
Are you looking for this?
SELECT s.*, c.country, c.clientname
FROM server s LEFT JOIN client c
ON s.clientid = c.clientid
Here is SQLFiddle demo.
For better understanding of JOINs see A Visual Explanation of SQL Joins

Multiple LEFT JOINS on the same table, using data from previous JOIN

I am using a LEFT JOIN in mysql to look up an organisation from a code which is in my dataset.
So the datatable might contain the orgcode 123
Then the orgtable contains the orgname of the organisation ie 'The Local Bookstore'.
However the orgtable also contains another code which identifies the parent organisation of the 'The Local Bookstore', using another code ie 456.
How do I write a query that goes to the orgtable, looks up the orgname, also finds the parentorgcode and then looks that up in the same table to find the parent organisation name as well?
Basically using the output of one LEFT JOIN to generate another LEFT JOIN in the same query...
Thanks
First things first, if you are managing a hierarchy of data I highly recommend reading http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ as it will show you various methods to store it which may well allow you to use a more optimal method than you currently are.
Secondly, you can LEFT JOIN easily enough as you have asked but just need to make sure each new join uses an alias so that there is no ambiguity as to which field you request, i.e.
SELECT
*
FROM datatable AS d
LEFT JOIN orgtable AS o1 ON o1.orgID = d.orgID
LEFT JOIN orgtable AS o2 ON o2.orgID = o1.parentOrgID
What you cannot do is automatically make MySQL keep adding on LEFT JOIN's until there is no parent. For that you will need either a recursive stored procedure, a looping stored procedure, or a nested tree (see link)
try to use alias like this:
SELECT tb1.orgcode, tb2.orgcode
FROM orgtable AS tb1 LEFT OUTER JOIN orgtable AS tb2 ON tb1.orgcode = tb2.orgcode
SELECT O1.NAME AS ORG_NAME, O2.NAME AS PARENT_ORG_NAME
FROM DATATABLE D
JOIN ORGANISTION O1
ON D.ORGID = O1.ORG_ID
LEFT JOIN ORGANISTION O2
ON O1.PARENT_ID = O2.ID

Group By in stored procedure error

I created this stored procedure which is basically to return a list of offices with the type of activities that happen within each office. The results i reported to reportviewer but i noticed that for each activity return it creates a table - so i can have 5 different tables each with its own activity but all happen in the same office. I want the report to be a table for each office which will contain as many activites as there are for each office. So i thought that if i grouped in my stored procedure my results will be as what i want but i am getting column error saying: "...is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
I am not sure how to go about that but here is my select, from, where, group by statements:
SELECT
O.OfficeId,
O.OfficeName AS Office,
HT.Description AS HearingType,
H.HearingDate AS HearingDate,
CR.Description AS Court,
CT.[Description]AS CaseType
FROM Activity H
INNER JOIN ActivityEntry HE ON H.ActivityEntryId = HE.ActivityEntryId
INNER JOIN ActivityType HT ON H.ActivityTypeId = HT.ActivityTypeId
INNER JOIN [Case] C ON H.CaseId = C.CaseId
INNER JOIN [Office] O ON HE.CreatedByOfficeId = O.OfficeId
INNER JOIN [User] U ON C.CreatedByUserId = U.UserId
LEFT OUTER JOIN CaseType CT ON C.CaseTypeId = CT.CaseTypeId
LEFT OUTER JOIN Court CR ON C.CourtId = CR.CourtId
WHERE .dbo.DateOnly(HE.HearingDate)BETWEEN #BeginDate AND #EndDate
GROUP BY
O.OfficeId,
O.OfficeName,
HT.Description
ORDER BY O.OfficeId, HT.Description
GROUP BY requires that you have some kind of an aggregate function in your list of columns - a SUM, an AVG, a COUNT. GROUP BY only makes sense in combination with an aggregate.
Otherwise, just simply order your data with an ORDER BY statement.
You aren't using any aggregate functions (on first glance anyway) so you don't need a group by clause. You can do all your ordering in the order by and then extract it into different datasets as you process it on the application side.
Example:
select ... from ... order by OfficeID, Description
This returns a single result for all offices. Now you need to parse it in code
int OfficeID=-1;
while(recordset.moveToNextRow())
{
if(currentRecord.OfficeID!=OfficeID)
{
//This is a new office, do whatever you need to do to split the data up here
OfficeID=currentRecord.OfficeID;
}
//Process the record as a part of the current office here
}
So if you were building a table on a webpage, you'd maybe end the last table and start a new table every time you hit a new office ID. There's some additional logic you'll need here, but this should give you the idea.
Note that your problem has nothing to do with using a stored procedure and everything to do with how you are selecting and processing data.
I actually realized that my problem cannot be solved through my stored procedure as mentioned from some of the members. Since i am displaying results in my report so i re-organized my report and dataset information so that there is a parent and child relationship and from the dataset my information was organized properly. I used the solutions offered from this post to help guide me: post used to help guide me.