Results I'd like to achieve: One record for each customer.
Number of tables: 3 (Account Master, MeterStatus, Codes.MeterStatus)
Hello, I'm trying to find one record for each customer in the following tables, Account Master, MeterStatus, Codes.MeterStatus. Account Master contains customers who are active (need to find here if its available), Meterstatus table contains customers who have been enrolled in our system, but might not have made it to active status, and codes.meterstatus is simply used to decipher codes that are located in meterstatus table.
I've already tried the following variations, but they have not provided the results I expected.
Select *
FROM [xx].[dbo].[AccountMaster] EAM
full join [xx].[Link].[MeterStatus] MS on ms.UAN = eam.UAN
left join xx.codes.MeterStatus on ms.MeterStatus = MeterStatus.MeterStatus
where eam.UAN in ('055013920') or ms.UtilityAccountNumber in ('055013920')
and ms.MeterStatus not in ('4','5')
FROM [xx].[Link].[MeterStatus] MS
left join xx.dbo.AccountMaster EAM on ms.UAN = eam.UAN
left join xx.codes.MeterStatus on ms.MeterStatus = MeterStatus.MeterStatus
where ms.UANin ('055013920')
and ms.MeterStatus not in ('4','5')
Related
I'm new to the working world an am fresh out of varsity. i started working an am creating a few reports via SQL reporting services as part of my training.
Here is quite a challenge that I am stuck at. Please help me finish this query. Here is how it goes!
There are several employees in the employee_table that each have unique identifier known as the emp_id
There is a time_sheet table that consists of several activities AND THE HOURS FOR EACH ONE for the employees and references them via emp_id. Each activity has a TIMESHEET_DATE that corresponds to the day all the activities were submitted(once a month). There are several activities with the same date because all those activities were submitted on the same day.
And there is a leave table that references the employees via emp_id. In the leave table, there is a column for the amount of days they took off and the starting day (Leave_FROM) of the leave.
I must create a parameter where the user inputs the month (easy peasy)...
Now in the report, column 1 must have their name (easy), column 2 must have their totals hours for the specified month (HOURS) and column 3 must show how many days they took leave for that month specified.
It can be tricky, not everybody has a entry in the leavetable, but everybody has got activities in the Time_Sheet table.
Here is what I have gotten so far from a query, but its not really helping me.
Unfortunately, I cannot upload pictures, so here is a link
http://imageshack.com/a/img822/8611/5czv.jpg
Oh yea, my flavor of SQL is SQL Server
You have a few different things you need to attack here.
First is getting information from the employee_table, regardless of what is in the other two tables. To do this, I would left join on both of the tables.
Your second battle is, now since you have multiple rows in your time_sheet table, you are going to get a record for every time_sheet record. That is not what you want. You can fix this by using a SUM Aggregate and a GROUP BY clause.
Next is the issue that you are going to have when nothing exists in leave table and it is returning NULL. If you add an ISNULL(value,0) around your leave table field, it will return 0 when no records exist on that table (for that employee).
Here is what your query should look like (not exactly sure on table/column naming):
I changed the query to use temp tables, so totals are stored separately. Since the temp tables will hold 0 for employees that don't have time/leave, you can do an inner join on your final query. Check this out for more information on temp tables.
SELECT e.emp_id, ISNULL(SUM(ts.Hours),0)[Time]
INTO #TotalTime
FROM employee e
LEFT JOIN time_sheet ts ON e.emp_id = ts.emp_id
GROUP BY e.emp_id
SELECT e.emp_id, ISNULL(SUM(l.days),0) [LeaveTime]
INTO #TotalLeave
FROM employee e
LEFT JOIN leaveTable l ON e.emp_id=l.emp_id
GROUP BY e.emp_id
SELECT e.Emp_Id,Time,LeaveTime FROM Employee e
INNER JOIN #TotalTime t ON e.Emp_Id=t.Emp_Id
INNER JOIN #TotalLeave l ON e.Emp_Id=l.Emp_Id
DROP TABLE #TotalLeave,#TotalTime
Here is the SQL Fiddle
Left join the leave table, if nobody took leave you won't get any results.
I have several views and tables which I am trying to connect in one view to create a website GUI for several users (and myself) to use. It is basically an inventory system which is linking together purchase information which has been dumped into a SQL table + internal asset tag + user accessing. Tables are similar to:
Assets - Serial Number, ID
UserAudit - UserName, AssetsID, OfficeID, date/time
Office - location
Orders - Serial Number, detail
Several of the assets are Computers and the UserAudit is populated by a logon script which records the users name, computers name, and date/time. I am trying to create a view which links all of the information based upon Assets list regardless of if they related tables have matching data. For the UserAudit side I just want to display the most recent record (date field Desc).
The place I am running into an issue is grabbing just the top record from the UserAudit based upon the ComputerName while still returning all of the columns from the others. I tried creating a separate view for the UserAudit with showing 'Top 1' - this however limited the main view to only 1 result as well if I use an "inner Join" and doesn't display anything from the UserAUdit when using any OUTER join.
I did some research in which a Cross Apply looks like it might be relevant, however I have not used this before and attempts have not worked well. The view currently looks like:
SELECT TOP (100) PERCENT
dbo.AssetType.AssetType, dbo.AssetTagInventory.ID, dbo.AssetTagInventory.AssetDetail,
dbo.AssetTagInventory.Name, dbo.AssetTagInventory.Serial, dbo.AssetTagInventory.UserID,
dbo.AssetTagInventory.Age, dbo.AssetTagInventory.Notes,
dbo.vewOffices.Name AS OfficeName,
dbo.AssetTagPurchases.PurchaseDate, dbo.AssetTagPurchases.ProductDescription AS Model,
dbo.AssetTagPurchases.ID AS AECOrderNumber,
dbo.AssetTagPurchases.Vendor, dbo.AssetTagPurchases.QuotedPrice,
dbo.AssetTagPurchases.InvoicedPrice, dbo.AssetTagPurchases.InvoiceNum,
dbo.AssetTagPurchases.VendorOrderNumber, dbo.vewLogonAudit.Username,
dbo.vewLogonAudit.LoginTime
FROM
dbo.AssetTagInventory
INNER JOIN
dbo.vewLogonAudit ON dbo.AssetTagInventory.Name = dbo.vewLogonAudit.ComputerName
LEFT OUTER JOIN
dbo.AssetType ON dbo.AssetTagInventory.AssetTypeID = dbo.AssetType.ID
LEFT OUTER JOIN
dbo.vewOffices ON dbo.AssetTagInventory.OfficeID = dbo.vewOffices.ID
LEFT OUTER JOIN
dbo.AssetTagPurchases ON dbo.AssetTagInventory.Serial = dbo.AssetTagPurchases.Serial
Take a look at OUTER APPLY. It should be just what you need here.
It should work with something like (among/after the other joins):
OUTER APPLY
( SELECT TOP 1 <columns>
FROM dbo.UserAudit
WHERE dbo.AssetTagInventory.<??> = dbo.UserAudit.<??>
ORDER BY <...>
) T_UserAudit
EDIT
Try using a unique alias after the closing brackets:
OUTER APPLY(...) TLA
And then in the Select-Part, use the alias without dbo.
SELECT .., ... , TLA.UserName
Maybe that's the only little bit to get it going.
I am trying to convert a view from an Oracle RDBMS to SQL Server. The view looks like:
create or replace view user_part_v
as
select part_region.part_id, users.id as users_id
from part_region, users
where part_region.region_id in(select region_id
from region_relation
start with region_id = users.region_id
connect by parent_region_id = prior region_id)
Having read about recursive CTE's and also about their use in sub-queries, my best guess at translating the above into SQL Server syntax is:
create view user_part_v
as
with region_structure(region_id, parent_region_id) as (
select region_id
, parent_region_id
from region_relation
where parent_region_id = users.region_id
union all
select r.region_id
, r.parent_region_id
from region_relation r
join region_structure rs on rs.parent_region_id = r.region_id
)
select part_region.part_id, users.id as users_id
from part_region, users
where part_region.region_id in(select region_id from region_structure)
Obviously this gives me an error about the reference to users.region_id in the CTE definition.
How can I achieve the same result in SQL Server as I get from the Oracle view?
Background
I am working on the conversion of a system from running on an Oracle 11g RDMS to SQL Server 2008. This system is a relatively large Java EE based system, using JPA (Hibernate) to query from the database.
Many of the queries use the above mentioned view to restrict the results returned to those appropriate for the current user. If I cannot convert the view directly then the conversion will be much harder as I will need to change all of the places where we query the database to achieve the same result.
The tables referenced by this view have a structure similar to:
USERS
ID
REGION_ID
REGION
ID
NAME
REGION_RELATIONSHIP
PARENT_REGION_ID
REGION_ID
PART
ID
PARTNO
DESCRIPTION
PART_REGION
PART_ID
REGION_ID
So, we have regions, arranged into a hierarchy. A user may be assigned to a region. A part may be assigned to many regions. A user may only see the parts assigned to their region. The regions reference various geographic regions:
World
Europe
Germany
France
...
North America
Canada
USA
New York
...
If a part, #123, is assigned to the region USA, and the user is assigned to the region New York, then the user should be able to see that part.
UPDATE: I was able to work around the error by creating a separate view that contained the necessary data, and then have my main view join to this view. This has the system working, but I have not yet done thorough correctness or performance testing yet. I am still open to suggestions for better solutions.
I reformatted your original query to make it easier for me to read.
create or replace view user_part_v
as
select part_region.part_id, users.id as users_id
from part_region, users
where part_region.region_id in(
select region_id
from region_relation
start with region_id = users.region_id
connect by parent_region_id = prior region_id
);
Let's examine what's going on in this query.
select part_region.part_id, users.id as users_id
from part_region, users
This is an old-style join where the tables are cartesian joined and then the results are reduced by the subsequent where clause(s).
where part_region.region_id in(
select region_id
from region_relation
start with region_id = users.region_id
connect by parent_region_id = prior region_id
);
The sub-query that's using the connect by statement is using the region_id from the users table in outer query to define the starting point for the recursion.
Then the in clause checks to see if the region_id for the part_region is found in the results of the recursive query.
This recursion follows the parent-child linkages given in the region_relation table.
So the combination of doing an in clause with a sub-query that references the parent and the old-style join means that you have to consider what the query is meant to accomplish and approach it from that direction (rather than just a tweaked re-arrangement of the old query) to be able to translate it into a single recursive CTE.
This query also will return multiple rows if the part is assigned to multiple regions along the same branch of the region heirarchy. e.g. if the part is assigned to both North America and USA a user assigned to New York will get two rows returned for their users_id with the same part_id number.
Given the Oracle view and the background you gave of what the view is supposed to do, I think what you're looking for is something more like this:
create view user_part_v
as
with user_regions(users_id, region_id, parent_region_id) as (
select u.users_id, u.region_id, rr.parent_region_id
from users u
left join region_relation rr on u.region_id = rr.region_id
union all
select ur.users_id, rr.region_id, rr.parent_region_id
from user_regions ur
inner join region_relation rr on ur.parent_region_id = rr.region_id
)
select pr.part_id, ur.users_id
from part_region pr
inner join user_regions ur on pr.region_id = ur.region_id;
Note that I've added the users_id to the output of the recursive CTE, and then just done a simple inner join of the part_region table and the CTE results.
Let me break down the query for you.
select u.users_id, u.region_id, rr.parent_region_id
from users u
left join region_relation rr on u.region_id = rr.region_id
This is the starting set for our recursion. We're taking the region_relation table and joining it against the users table, to get the starting point for the recursion for every user. That starting point being the region the user is assigned to along with the parent_region_id for that region. A left join is done here and the region_id is pulled from the user table in case the user is assigned to a top-most region (which means there won't be an entry in the region_relation table for that region).
select ur.users_id, rr.region_id, rr.parent_region_id
from user_regions ur
inner join region_relation rr on ur.parent_region_id = rr.region_id
This is the recursive part of the CTE. We take the existing results for each user, then add rows for each user for the parent regions of the existing set. This recursion happens until we run out of parents. (i.e. we hit rows that have no entries for their region_id in the region_relationship table.)
select pr.part_id, ur.users_id
from part_region pr
inner join user_regions ur on pr.region_id = ur.region_id;
This is the part where we grab our final result set. Assuming (as I do from your description) that each region has only one parent (which would mean that there's only one row in region_relationship for each region_id), a simple join will return all the users that should be able to view the part based on the part's region_id. This is because there is exactly one row returned per user for the user's assigned region, and one row per user for each parent region up to the heirarchy root.
NOTE:
Both the original query and this one do have a limitation that I want to make sure you are aware of. If the part is assigned to a region that is lower in the heirarchy than the user (i.e. a region that is a descendent of the user's region like the part being assigned to New York and the user to USA instead of the other way around), the user won't see that part. The part has to be assigned to either the user's assigned region, or one higher in the region heirarchy.
Another thing is that this query still exhibits the case I mentioned above about the original query, where if a part is assigned to multiple regions along the same branch of the heirarchy that multiple rows will be returned for the same combination of users_id and part_id. I did this because I wasn't sure if you wanted that behavior changed or not.
If this is actually an issue and you want to eliminate the duplicates, then you can replace the query below the CTE with this one:
select p.part_id, u.users_id
from part p
cross join users u
where exists (
select 1
from part_region pr
inner join user_regions ur on pr.region_id = ur.region_id;
where pr.part_id = p.part_id
and ur.users_id = u.users_id
);
This does a cartesian join between the part table and the users table and then only returns rows where the combination of the two has at least one row in the results of the subquery, which are the results that we are trying to de-duplicate.
I am building an application for my semestre exam which will take place in 20 days. My app should assist teachers to build more easily our faculty timetable.
I am working with a database approach (Sql Server 2008 and Delphi XE2). I have a few tables that describe the student formations structure. So I have Years, Series, Specializations, Groups and SemiGroups. Like in the image Years contains Series, Series contain Specializations, Specializations contains Groups and Groups may contain or not SemiGroups. I have also tables with Courses, Teachers, ClassRooms, Days and HourlyIntervals.
There are a few conditions:
A teacher may take a course with one or more Specializations, OR with one or more Groups, OR with one or more Semigroups.
The second condition is that Courses are of 3 types: TeachingCourse, Seminary, Laboratory (only two from three possible for each CourseName).(stored in the column Scheduler.CourseType char(3) )
The third one: Courses can be kept in all weeks of a semester, or in oddweek numbers,or in weeks number dividable by 2.(stored in the column Scheduler.Week char(3))
So I am storing the correlations in a SchedulerTable.
So if a Group has a course with a certain teacher I will introduce only the corresponding IDs.
I built almost all the data introducing forms and now I am at the Reporting part of the application. I am using Report Services from MSSQL 2008.
I want to list a scheduler that will include all the correlations for a certain Specialization (that one includes Groups and/or Semigroups). I have managed to show all correlations for Groups belonging to that certain Specializations but I can't manage to show alse the Specialization and Semigroups courses.
This is the query that returns me Groups correlations from a certain Specialization.
SELECT Days.DayName, HourlyIntervals.HourlyIntervalName, Scheduler.Week, Scheduler.CourseType, Courses.CourseName, ClassRooms.ClassRoomName, Teachers.TeacherName,Specializations.SpecName, Groups.GroupsName
FROM Scheduler INNER JOIN
Groups ON Scheduler.GroupID = Groups.GroupID INNER JOIN
Days ON Scheduler.DayID = Days.DayID INNER JOIN
HourlyIntervals ON Scheduler.HourlyIntervalID = HourlyIntervals.HourlyIntervalID INNER JOIN
Teachers ON Scheduler.TeacherID = Teachers.TeacherID INNER JOIN
Courses ON Scheduler.CourseID = Courses.CourseID INNER JOIN
ClassRooms ON Scheduler.ClassRoomID = ClassRooms.ClassRoomID INNER JOIN
Specializations ON Groups.IDSpec = Specializations.IDSpec
WHERE (Specializations.ID = #SpecID)
ORDER BY Days.DayID, HourlyIntervals.HourlyIntervalID
But I want it to return corelations for SemiGroups,Groups and Specialization for that certain Specialization. I tried to add a join with this one Scheduler.SemiGroupID=Semigroups.SemigroupID but the query returns 0 results then. I don't know if it can be done what I want but I will be thankful to anyone that points me an idea. Or should I use another structure for my correlations table (SchedulerTable).
This is a sample report (a PDF file) which I would like to get:
Edit Reason: Better explaining of the issue
So why isn't this the solution?
SELECT Days.DayName, HourlyIntervals.HourlyIntervalName, Scheduler.Week, Scheduler.CourseType, Courses.CourseName, ClassRooms.ClassRoomName, Teachers.TeacherName,Specializations.SpecName, SemiGroups.GroupsName
FROM Scheduler
INNER JOIN SemiGroups On Scheduler.SemiGroupId = SemiGroups.SemiGroupId
INNER JOIN Groups ON SemiGroups.GroupID = SemiGroups.Groups
INNER JOIN Days ON Scheduler.DayID = Days.DayID
INNER JOIN HourlyIntervals ON Scheduler.HourlyIntervalID = HourlyIntervals.HourlyIntervalID
INNER JOIN Teachers ON Scheduler.TeacherID = Teachers.TeacherID
INNER JOIN Courses ON Scheduler.CourseID = Courses.CourseID
INNER JOIN ClassRooms ON Scheduler.ClassRoomID = ClassRooms.ClassRoomID
INNER JOIN Specializations ON Groups.IDSpec = Specializations.IDSpec
WHERE (Specializations.ID = #SpecID)
ORDER BY Days.DayID, HourlyIntervals.HourlyIntervalID
Though I'll admit to a furrowed brow about whether GroupID in Schedules was the GroupID of the SemiGroupID in that row. Looks likes that bit isn't normalised.
I have a query that I'm not sure how to write. I'm not a SQL expert and it's pretty nasty. I'm hoping someone here can help me with it.
I have a table called "Members" which has a list of user names to my web site. I need to get the list of users that belong to one or more divisions in my company as well as one or more managers. The specific divisions and managers are chosen by a user in my web site. I have a list of the managers and divisions they have selected. I have also parsed them into a comma-delimited list. Here is a summary of the table information I am trying to link together:
Members
UserName
StoreID
Store
StoreID
PostalCode
Division
PostalCode
ManagerID
Manager
ManagerID
ManagerName
How do I get the list of Members based on a list of Regions and Managers that a user chooses? Sincerely thank you for your help!
Select Members.UserName
From Members
Join Store On Members.StoreID = Store.StoreID
Join Division On Store.PostalCode = Division.PostalCode
Join Manager On Division.ManagerID = Manager.ManagerID
Where Division.PostalCode In (12345, 12346)
And Manager.ManagerID In (1, 2, 3, 4)
You say you have a list of managers and divisions. Do you have ManagerID and PostalCode? If so, you don't need to join in the manager table as both of these are found in the division table.
SELECT
Members.UserName
FROM
Members
INNER JOIN
Store
ON
Members.StoreID = Store.StoreID
INNER JOIN
Division
ON
Store.PostalCode = Division.PostalCode
WHERE
Division.PostalCode IN (Use comma delimited postal codes here)
AND
Division.ManagerID IN (Use comma delimited manager ids here)