I have a used query as follows:
SELECT LTRIM(RTRIM(ClaimsAdminName)) + ' | ' + LTRIM(RTRIM(ClaimsAdminID)) AS Clientname
FROM tblClaimsAdmin
WHERE (ClaimsAdminName LIKE #Prefix)
UNION
SELECT LTRIM(RTRIM(EmployerFName + ' ' + EmployerLName)) + ' | ' + LTRIM(RTRIM(EmployerID)) AS Clientname
FROM tblEmployer
WHERE (EmployerFName LIKE #Prefix)
The result returned if I enter 's%' is :
s | 8
Sumit Singh | 16
Now is there any way so that i can return the tablename with the result set.Like from which table the value is coming.
I hope I am clear with my query.
Please help!
Thanks
Swaroop Kumar.P
select 'table1' as tablename, otherfields
from table1
union all
select 'table2', otherfields
from table2
Related
I realize i'm far off the solution with what i have:
Select FirstName || ' ' || LastName AS Manager From Employee
Where (Select COUNT(ReportsTo) from Employee
group by ReportsTo
order by ReportsTo desc);
ReportsTovalues are the EmployeeID they report to
What i want is to query the name of the employee with the most Employees reporting to them and who they in turn report to without nulls. I'm Not sure how to make the connections between columns values such as ReportsTo to EmployeeID so any explanation would help
For Example the output i would want is two columns say | Fred Jones | Mary Anne| the first being the employee with the most reportsTo with the same value as their EmployeeID and the second being the name of the employee with the same EmployeeID as the first employees ReportTo
Do this step by step:
First step: Count how many employees report to a person.
select reportsto, count(*) from employee group by reportsto;
We can order this result by count(*) and limit it to only get one row, so as to get the person with the most reporters. Only problem is: What to do in case of ties, i.e. two persons have the same highest amount of reporters? SQLite doesn't offer much to help here. We'll have to query twice:
select reportsto
from employee
group by reportsto
having count(*) =
(
select count(*)
from employee
group by reportsto
order by count(*) desc
limit 1
);
Next step: Get the name. That means we must access the table again.
select
firstname || ' ' || lastname as manager
from employee
where e1.employeeid in
(
select reportsto
from employee
group by reportsto
having count(*) =
(
select count(*)
from employee
group by reportsto
order by count(*) desc
limit 1
)
);
Last step: Get the persons our found managers themselves report to. These can be many, so we group by manager and concatenate all those they report to.
select
e1.firstname || ' ' || e1.lastname as manager,
group_concat(e2.firstname || ' ' || e2.lastname) as reportsto
from employee e1
join employee e2 on e2.employeeid = e1.reportsto
where e1.employeeid in
(
select reportsto
from employee
group by reportsto
having count(*) =
(
select count(*)
from employee
group by reportsto
order by count(*) desc
limit 1
)
)
group by e1.firstname || ' ' || e1.lastname;
SELECT e.ReportsTo AS TopManagersEmployeeId, COUNT(e.ReportsTo) AS ReportedBy, m.FirstName + ' ' + m.LastName AS TopManagersName, mm.FirstName + ' ' + mm.LastName AS TheirManagersName FROM Employees e
JOIN Employees m
ON e.ReportsTo = m.EmployeeID
JOIN Employees mm
ON m.ReportsTo = mm.EmployeeID
GROUP BY e.ReportsTo, m.FirstName, m.LastName, mm.FirstName, mm.LastName
Once you have this data, you can do TOP 1 etc. You can also play around with JOIN, and make it INNER JOIN in the second set where Manager's Manager (mm) is being retrieved.
i have the following table friend
id | first_name | last_name | gender | age | mobile
1 | bobby | roe | male | 21 | 541-5780
how to concatenate multiple column (first_name & last_name) values into a single column to get the following result?
full_name
bobby roe
i have writen the following query but it does not work
declare #full_name varchar(max)
select #full_name = COALESCE(#full_name + ', ', '') + first_name, last_name
from friend
select #full_name
More than one way to achieve this:
SELECT CONCAT(first_name, ' ' ,last_name) AS full_name;
For earlier versions (Where CONCAT is not a built in function):
SELECT first_name + ISNULL(' ' + last_name, '') as Full_Name from [YourTable]
This as well should give you the same result
SELECT COALESCE(first_name, '') + COALESCE(last_name, '') as FullName FROM [YourTable]
I have this select statement:
SELECT *
FROM Room
LEFT JOIN booking ON (Room.RoomId = booking.RoomId)
WHERE booking.Roomid is null
AND GETDATE() BETWEEN bookin.checkindate '" + TxtCheckIn.Text + "'
AND booking.checkoutdate '" + TxtCheckOut.Text + "'" + "
ORDER BY Room.RoomType
I want to check in the booking table if the date matches the checkin and checkout dates selected by users. If it doesn't match, the query should show all rooms in the room table (even if it is in the booking table), provided that they have different dates.
You need to determine whether any rows match the condition on the date. To do this, the following query moves the date condition into the on clause. Then it uses the window function count() to count the number of matches. If there are none, then all rows are returned. Otherwise, only matches are returned.
select t.*
from (SELECT *, count(booking.RoomId) over () as numMatches
FROM Room LEFT JOIN
booking
ON Room.RoomId = booking.RoomId and
GETDATE() BETWEEN booking.checkindate '" + TxtCheckIn.Text + "' and
booking.checkoutdate '" + TxtCheckOut.Text + "'" + "
) t
where numMatches > 0 and RoomId is not null or numMatches = 0
ORDER BY Room.RoomType
Is it possible to add carriage returns and line feeds into the CommandText of a TableAdapter so the results of the query displays them in an ASP.Net GridView?
Here is part of a query in the TableAdapter I made using the DataSet designer:
SELECT AsthmaTreatment,
BookFee, ClinicWhenIll, DateOfBirth, Forename, GPA, Grade, HealthProblems, ID,
IllnessDetails, InjuryDetails, InsuranceCompany, InsurancePolicyNumber,
LanguagesSpoken, MedicinesTaken, ParentID,
(SELECT MotherName + ' *** ' + FatherName + '***' + CHAR(13) + CHAR(10) +
AddressLine1 + CHAR(13) + CHAR(10) +
AddressLine2 + CHAR(13) + CHAR(10) +
City + ', ' + State + ' ' + Zip AS Expr1
FROM Parents WHERE (ID = Students.ParentID)) AS ParentName,
PrimaryDoctor, PrimaryDoctorPhone, PrimaryPhone, SecondaryPhone,
SurgeryDetails, Surname, TuitionFee, email
FROM Students
WHERE (Forename LIKE '%' + #SearchValue + '%') OR
(Surname LIKE '%' + #SearchValue + '%') OR
(#SearchValue = 'ALL')
Using the query described above, the GridView data is shown without the carriage returns and line feeds separating the lines of data.
We are looking to show the data like this in the GridView:
Ismail Eva *** Emad-ud-deen ***
123 Test St
Apt. 100
New York, NY 10021
Mustafa Eva *** Emad-ud-deen ***
333 First Ave.
Unit 3-B
Lowell, MA 01852
the problem is the character's themselves. (browsers, html) do not translate char 10 & 13. Browsers do undertand HTML markup, so you can use <p>, <div>, or <br> tags to format the text.
I would do this in the HTML markup though, not the sql statement.
I am sending you the details that i am in mess.
below I am describing.
Original Table Structure.
ID Date TimeLogged(Hrs) UserName
1 10/8/2012 5.50 Bubai
2 11/8/2012 2.30 Bubai
3 10/8/2012 3.30 Bhanu
4 11/8/2012 7.30 Bhanu
I want result like below. User Name should be dynamic. May be lot of
users. User name will come from Database table.
I want to show details in Gridview(Front End).explain broadly as I am very new in development.
Date Bubai Bhanu Total
10/8/2012 5.30 3 8. 30
11/8/2012 2.30 7.30 10
Total 8 10.30 18.30
You can use a PIVOT for this, either a Static or Dynamic. You can place this code in a stored procedure and populate your datagrid with it.
Static Pivot (See SQL Fiddle with Demo) This means you will hard code all values:
select convert(char(10), dt, 101), [Bubai], [Bhanu], ([Bubai] + [Bhanu]) total
from
(
select dt, timelogged, username
from test
)x
pivot
(
sum(timelogged)
for username in ([Bubai], [Bhanu])
)p
union all
select 'total', sum([Bubai]), sum([Bhanu]), sum([Bubai] +[Bhanu])
from
(
select dt, timelogged, username
from test
)x
pivot
(
sum(timelogged)
for username in ([Bubai], [Bhanu])
)p
Dynamic Pivot (See SQL Fiddle with Demo), this will get the list of fields to transform at run-time:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX),
#totalCol AS NVARCHAR(MAX),
#totalRow AS NVARCHAR(MAX)
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.username)
FROM test c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #totalCol = STUFF((SELECT distinct '+' + QUOTENAME(c.username)
FROM test c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #totalRow = STUFF((SELECT distinct ',Sum(' + QUOTENAME(c.username) + ')'
FROM test c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT convert(char(10), dt, 101), ' + #cols + ', '+#totalCol +' total from
(
select dt, timelogged, username
from test
) x
pivot
(
sum(timelogged)
for username in (' + #cols + ')
) p
union all
select ''total'', '+ #totalRow +', sum('+#totalCol+')
from
(
select dt, timelogged, username
from test
)x
pivot
(
sum(timelogged)
for username in (' + #cols + ')
)p'
execute(#query)
Both of these will produce the same results.
#NikolaMarkovinović is right, you should get the results you need using a pivot query, the problem is you have to know the values in the column you want to pivot
SELECT Date , [Bunbai] , [Bhanu] , ..., /* This names have to be known, the same as in the IN part of the PIVOT */
/* You can even do this */
[Bunbai]+[Bhanu] AS Total
FROM ( <SELECT query that produces the data> ) AS T
PIVOT ( SUM( TimeLoggedHours ) FOR UserName
IN ( [Bunbai] , [Bhanu] , ... )
/* You can't write some subquery inside the IN, columns names have to be known */
) AS pvt
, you will need to write a Dinamic Query Method in you code to, first get the names of the columns, then add them in the headers of the query and the IN part of the PIVOT.
To add the totals at the bottom just write the same query but in the query that produces the data, instead of the date select 'Total' and use UNION ALL
Hope this helps.