Insert sum of rows and display it in the same table - sql-server

I have a table as shown below
I want to insert the row below each employee having data as like same employeecode, employeename, project as 'bench', expected end & start dates as null , install capacity as sum of all install capacities of that employees-184 and allocation % as null.
Result should look like this.
Thanks in advance.

Try This:
INSERT INTO TABLE_NAME SELECT EMPLOYEEDODE, EMPLOYEENAME, 'BENCH' AS PROJECTNAME, NULL AS START_DT, NULL AS ENDDT, SUM(install_capacities), SUM(ActualPercentage) FROM TABLE_NAME GROUP BY EMPLOYEEDODE,EMPLOYEENAME;

Please try the below queries to produce the desired output:
insert into tbl(EmployeeCode, EmployeeName, projectName,ExpectedStartDate, ExpectedEndDate, InstallCapacity, [Actual Allocation Percentage])
select EmployeeCode,EmployeeName,'Bench' As projectName,NULL as ExpectedStartDate, NULL as ExpectedEndDate, SUM(InstallCapacity) as InstallCapacity, SUM([Actual Allocation Percentage]) as [Actual Allocation Percentage]
from tbl
group by EmployeeCode,EmployeeName
select * from tbl order by EmployeeCode,EmployeeName

Related

SQL Grouping and Counting based on dates

Getting nowhere here and seems so simple.
Test data is:
declare #table table(SpellAdminsionDate datetime, SpellDischargeDate datetime, Pat_code varchar(10))
insert into #table (SpellAdminsionDate, SpellDischargeDate, Pat_code) values('2016-09-12 15:55:00:000','2016-09-19 20:20:00:000','HEY3052275')
insert into #table(SpellAdminsionDate, SpellDischargeDate, Pat_code) values ('2016-09-07 17:17:00:000','2016-09-17 18:40:00:000','HEY0810155')
insert into #table(SpellAdminsionDate, SpellDischargeDate, Pat_code) values ('2016-09-14 16:50:00:000','2016-09-17 18:01:00:000','HEY1059266')
insert into #table(SpellAdminsionDate, SpellDischargeDate, Pat_code) values ('2016-09-15 02:47:00:000','2016-09-15 17:28:00:000','HEY0742883')
insert into #table(SpellAdminsionDate, SpellDischargeDate, Pat_code) values ('2016-08-27 00:11:00:000','2016-09-14 12:49:00:000','HEY3050628')
insert into #table(SpellAdminsionDate, SpellDischargeDate, Pat_code) values ('2016-09-10 12:24:00:000','2016-09-13 20:00:00:000','HEY0912392')
insert into #table(SpellAdminsionDate, SpellDischargeDate, Pat_code) values ('2016-09-12 12:51:00:000','2016-09-13 19:55:00:000','HEY0908691')
Select * from #table`
Below is my simple code displaying the same thing:
SELECT c.SpellAdmissionDate,
c.SpellDischargeDate,
c.Pat_Code
FROM [CommDB].[dbo].[vwCivicaSLAM1617Live] c
WHERE c.Hrg_Code like 'VA%'
and c.Pat_Code like 'HEY%'
ORDER BY c.SpellDischargeDate desc
All I am after is a COUNT per day of active patients, for example take the 12/09/2016 on that date the result would be 5 (based on the test data) as the other 2 cam in after the 12th.
If it makes it easier I do have a date reference table called DATE_REFERENCE which has every date available to me.
Allowing for the possibility of having no patients on a day then you want to use your date reference table as the primary and left join to the patient information. You don't identify a column name so I just used [datecol].
SELECT
d.[datecol] the_date
, count(DISTINCT c.Pat_Code) num_patients
FROM DATE_REFERENCE d
LEFT JOIN [CommDB].[dbo].[vwCivicaSLAM1617Live] c
ON d.[datecol] BETWEEN c.SpellAdmissionDate AND c.SpellDischargeDate
AND c.Hrg_Code LIKE 'VA%'
AND c.Pat_Code LIKE 'HEY%'
GROUP BY
d.[datecol]
ORDER BY
d.[datecol] DESC
I suspect there may be more than this required, but without sample data and expected results it is difficult to know what you really need.
nb. I assume the date in that date_reference table is at midnight (00:00:00) or has a data type of date (without hours/minutes etc.)
Is this what you want?
SELECT dr.date,
(SELECT COUNT(*)
FROM [CommDB].[dbo].[vwCivicaSLAM1617Live] c
WHERE dr.date between c.SpellAdmissionDate and c.SpellDischargeDate) as cnt_per_day
FROM DATE_REFERENCE dr
Add the filters you want to the correlated query .
You can achieve this by joining to your date reference table and counting by a distinct of the patient reference
SELECT
dateRef
,COUNT(DISTINCT Pat_Code) AS PatCount
FROM #table t
RIGHT JOIN #date_reference
ON SpellAdminsionDate <= dateRef
AND SpellDischargeDate >= dateRef
GROUP BY dateRef;
Active count of patients per date can be achieved by (for temp data provided here)
SELECT DISTINCT CAST(T1.SPELLADMINSIONDATE AS DATE)
AdmissionDate,PATIENTS.TotalActive
FROM #TABLE T1
CROSS APPLY (SELECT COUNT(*)TotalActive FROM #TABLE T2 WHERE
CAST(T2.SPELLADMINSIONDATE AS DATE)<=CAST(T1.SPELLADMINSIONDATE AS DATE)) PATIENTS
I think you need to bring the DATE_REFERENCE table to the Query If it contains all the day dates that you need to count patients based on them, But here is a sample of how may you get the required result form this table only
Select DISTINCT c.SpellAdmissionDate, count(c.Pat_code) as PCounter
From [CommDB].[dbo].[vwCivicaSLAM1617Live] c
GROUP BY c.SpellAdmissionDate
ORDER BY c.SpellAdmissionDate desc

How to pivot rows to columns and column data under the new columns?

I have this table
http://sqlfiddle.com/#!3/641f9
and i would like to select it to look like this
How it is possible in Sql Server 2008 ?
It is really important to me, thank you.
I think this is what you want:
IF OBJECT_ID(N'tempdb..#Temp') IS NOT NULL
BEGIN
DROP TABLE #Temp
END
SELECT
sd.Company,
sd.Brand,
'DateFrom' AS Variable,
sd.DateFrom AS [Date],
sd.WeekName
INTO
#temp
FROM
dbo.SourceData AS sd
UNION ALL
SELECT
sd.Company,
sd.Brand,
'DateTo' AS Variable,
sd.DateTo AS [Date],
sd.WeekName
FROM
dbo.SourceData AS sd
SELECT
Company,
Variable,
Brand,
NOVW42012,
MAYW42014,
AUGW32014,
APRW12013,
AUGW52013,
MARW22014
FROM
(
SELECT
Company,
Variable,
Brand,
[Date],
WeekName
FROM
#temp
) sd PIVOT
( MIN(sd.[Date]) FOR WeekName IN (NOVW42012, MAYW42014, AUGW32014, APRW12013,
AUGW52013, MARW22014) ) AS PVT
ORDER BY
Company,
Brand

Can the below query be rebuilt using setbased rather than iterative logic

I am preparing one SSRS report and i have only select access in the table.
I have built the query to get the data.But since i am using table variables, and not getting the desired output in report.
Here is my table structure:
This table stores each job run data with below columns:
jobname
instance_id--ever increasing unique number for each run
starttime
endtime
status
I want to show in my report all above columns and I wrote the query like below.
since I want to show latest run irrespective of success or failure, I need to get max(instance_id) into one table and from that base table I am passing all in loop.
I am getting max instance_id along with row number for looping purposes
create table ##table
(
fqjn varchar(1000),
maxi int,
rownum int
)
create table ##tb
(jobname varchar(max),
[status] varchar(100),
duration int
)
insert into ##table
select jobname,max(instance_id) as maxi,row_number() over (order by jobname desc) as rownum from [dbo].[vw_job_hist]
where grp_data_id in (select grp_Data_id from [dbo].[vw_job_data] where grp_name='pcp')
group by jobname
--now loop through table passing instance_id as parameter
declare #rownum int
select top 1 #rownum=rownum from ##table order by rownum
while #rownum is not null
begin
insert into ##tb
select jh.jobname,"job status"=
case jh.completion_status
when 0 then 'Success'
else 'Failed'
end,
"duration"=datediff(minute,jh.started_time,jh.end_time)
from [dbo].[vw_job_] jh
where jh.instance_id in (select maxi from ##table where rownum=#rownum)
set #rownum=(select top 1 rownum from ##table where rownum>#rownum
order by rownum
end
select * from ##tb
drop table ##tb
drop table ##table
I am not getting the desired output in SSRS ,i know if i create the above query as stored proc,i will get the desired results.but this is third party database and we wont get access.
ask:
Can the above query logic be built in single query with out loop/cursor
I tried using recursive cte ,but no further progress
any help/pointers would be much appreciated
Try this:
;WITH OrderedJobInfo AS (
SELECT jobname, completion_status, started_time, end_time, instance_id
, ROW_NUMBER() OVER (PARTITION BY jobname ORDER BY instance_id DESC) AS rownum
FROM [dbo].[vw_job_hist]
WHERE grp_data_id IN (SELECT grp_Data_id FROM [dbo].[vw_job_data] WHERE grp_name='pcp')
)
SELECT o.jobname, o.instance_id
, [job status] = CASE o.completion_status WHEN 0 THEN 'Success' ELSE 'Failed' END
, [duration] = DATEDIFF(MINUTE, o.started_time, o.end_time)
FROM OrderedJobInfo o
WHERE o.rownum = 1;

Error in converting value from char to money

I have a table tableA that contains a column [Amount] of datatype varchar.
It has values like:
47980.89
333652.61
332388.84
374664.48
368715.26
371689.33
371689.33
368715.26
374664.48
Now when I run my query, it runs successfully but gives different output each time
SELECT
sum(convert(float, Amount))
FROM tableA
and when I try this other statement, I get an error
Cannot convert a char value to money. The char value has incorrect syntax.
Code:
SELECT
sum(convert(money, Amount))
FROM tableA
I want to have sum of the column [Amount]
this should do it:
select Sum(isnull(cast(amount as float),0)) from #t
or you need it to be money data-type
select Sum(isnull(cast(amount as money),0)) from #t
fiddle demo
Try Like this
SELECT SUM(CAST(Amount AS MONEY)) From TableA where ISNUMERIC(Amount)=1

Arrange rows in T-SQL

How to arrange rows manually in T-SQL?
I have a table result in order like this:
Unknown
Charlie
Dave
Lisa
Mary
but the expected result is supposed to be:
Charlie
Dave
Lisa
Mary
Unknown
edited:
My whole query is:
select (case when s.StudentID is null then 'Unknown' else s.StudentName end) as StudentName from Period pd full join Course c on pd.TimeID = c.TimeID full join Student s on c.StudentID = s.StudentID
group by s.StudentName, s.StudentID
order by case s.StudentName
when 'Charlie' then 1
when 'Dave' then 2
when 'Lisa' then 3
when 'Mary' then 4
when 'Unknown' then 5
end
but it didn't work. I think the problem root is because Unknown is from NULL value, as I wrote in that query that when StudentID is null then change "NULL" to "Unknown". Is this affecting the "stubborn" order of the result? By the way I also have tried order by s.StudentName asc but also didn't work.
Thank you.
Try the following...
SELECT os.StudentName
FROM ( SELECT CASE WHEN s.StudentID IS NULL THEN 'Unknown'
ELSE s.StudentName
END AS StudentName
FROM Period pd
FULL JOIN Course c ON pd.TimeID = c.TimeID
FULL JOIN Student s ON c.StudentID = s.StudentID
GROUP BY s.StudentName ,
s.StudentID
) AS os
ORDER BY os.StudentName
Edit: based on comment...
When I use this, it works fine...notice the Order By has no identifier
declare #tblStudent TABLE (StudentID int, StudentName varchar(30));
insert into #tblStudent values (null, '');
insert into #tblStudent values (1, 'Charlie');
insert into #tblStudent values (2, 'Dave');
insert into #tblStudent values (3, 'Lisa');
insert into #tblStudent values (4, 'Mary');
SELECT CASE WHEN s.StudentID IS NULL THEN 'Unknown'
ELSE s.StudentName
END AS StudentName
FROM #tblStudent s
GROUP BY s.StudentName ,
s.StudentID
ORDER BY StudentName
As I see your rows must be ordered alphabetically, so just add in the end of the query: ORDER BY p.StudentName.
If this not help, please add whole query, so we can find out the problem.
So when I see query I can explain. You try to sort by column p.StudentName. This column contains NULL. Try to sort by StudentName without p in front. This is alias of the expression which contains Unknown.
just put the following clause in you SQL statement:
order by p.StudentName
Sql server will order the column alphabetically.

Resources