When i used this to count how many employees working in each departments , its working fine :
-- Count
totals.Nr_Employees as TotalEmployees
LEFT JOIN
(select p1.DepartmentName, count(distinct u.Id) Nr_Employees
from Paychecks p1
join Users u on u.Id = p1.UserId
where u.customerid=214 and u.isdeleted=0
group by p1.DepartmentName
) totals on totals.DepartmentName = p.DepartmentName
BUT, when i want to make total of count or sum count , i do something like this ,but its not working and i dont know its right way to do or not ! Can someone please point me in the right direction?
-- SUM
SummerCount.TotalEmployees as sumEmployees
LEFT JOIN
(select p1.DepartmentName, sum(count(distinct u.Id)) TotalEmployees
from Paychecks p1
join Users u on u.Id = p1.UserId
where u.customerid=214 and u.isdeleted=0
group by p1.DepartmentName
) SummerCount on SummerCount.DepartmentName = p.DepartmentName
AND , put Querys together:
-- Count & SUM
totals.Nr_Employees as TotalEmployees,
SummerCount.TotalEmployees as sumEmployees
FROM
LEFT JOIN
(select p1.DepartmentName, count(distinct u.Id) Nr_Employees
from Paychecks p1
join Users u on u.Id = p1.UserId
where u.customerid=214 and u.isdeleted=0
group by p1.DepartmentName
) totals on totals.DepartmentName = p.DepartmentName
LEFT JOIN
(select p1.DepartmentName, sum(count(distinct u.Id)) TotalEmployees
from Paychecks p1
join Users u on u.Id = p1.UserId
where u.customerid=214 and u.isdeleted=0
group by p1.DepartmentName
) SummerCount on SummerCount.DepartmentName = p.DepartmentName
Screenshots (wrong sum):
Aggregate functions as operators of aggregate functions are not supported. This is, why your statment doe not work.
You can either use the WITH ROLLUP clause or put your statement into a subselect and build the sums in the outer statement.
Use a common table expression to get replace the first query, and select sum from that cte to replace the second one:
;WITH EmployeesCount AS
(
select p1.DepartmentName, count(distinct u.Id) Nr_Employees
from Paychecks p1
join Users u on u.Id = p1.UserId
where u.customerid=214 and u.isdeleted=0
group by p1.DepartmentName
)
And then, in your main query:
...
LEFT JOIN
EmployeesCount As totals on totals.DepartmentName = p.DepartmentName
LEFT JOIN
(
SELECT SUM(Nr_Employees)
FROM EmployeesCount
) As SummerCount on SummerCount.DepartmentName = p.DepartmentName
Update
;WITH EmployeesCount AS
(
select p1.DepartmentName, count(distinct u.Id) Nr_Employees
from Paychecks p1
join Users u on u.Id = p1.UserId
where u.customerid=214 and u.isdeleted=0
group by p1.DepartmentName
)
SELECT totals.Nr_Employees as TotalEmployees,
SummerCount.Nr_Employees as sumEmployees
FROM
dbo.Paychecks AS p INNER JOIN dbo.Users AS u ON u.Id=p.UserId
INNER JOIN dbo.EmploymentStatuses AS E ON E.Id = u.EmploymentStatusId
LEFT OUTER JOIN dbo.EmployeeTerminationQueue AS etq on etq.UserId = u.Id
LEFT OUTER JOIN dbo.TerminationReasons AS t on t.Id = etq.TerminationReasonid
LEFT JOIN EmployeesCount As totals on totals.DepartmentName = p.DepartmentName
CROSS JOIN
(
SELECT SUM(Nr_Employees) As Nr_Employees
FROM EmployeesCount
) As SummerCount
Full query
;WITH EmployeesCount AS
(
select p1.DepartmentName, count(distinct u.Id) Nr_Employees
from Paychecks p1
join Users u on u.Id = p1.UserId
where u.customerid=214 and u.isdeleted=0
group by p1.DepartmentName
)
SELECT DISTINCT u.Id, u.FirstName + ' ' + u.LastName AS Medarbajder,
u.SSN AS CPRNR,
(CASE
WHEN u.SSN IS NOT NULL THEN
DATEDIFF(YEAR,CONVERT(date,STUFF(LEFT(u.SSN, 4), 3, 0, '.') + '.' + CAST(DATEPART(YEAR, GETDATE()) / 100 - 1 as char(2)) + SUBSTRING(u.SSN, 5, 2), 104) , GETDATE())
ELSE
NULL
END) As Aldre ,
(CASE WHEN right(rtrim(SSN), 1) IN ('1', '3', '5', '7', '9') THEN 'M'
WHEN right(rtrim(SSN), 1) IN ('2', '4', '6', '8', '0') THEN 'K'
END) as Køn,
convert(varchar(10), p.WorkStartDate, 105) AS StartDato ,
(CASE
WHEN u.ResignationDate IS NOT NULL THEN
CONVERT(varchar(4), DATEDIFF(dd, WorkStartDate, u.ResignationDate)/365) + ' år '+
CONVERT(varchar(4), DATEDIFF(MONTH, WorkStartDate, u.ResignationDate) % 12) + ' måneder '+
CAST(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy, WorkStartDate, u.ResignationDate), WorkStartDate), u.ResignationDate),
DATEADD(yy, DATEDIFF(yy, WorkStartDate, u.ResignationDate), WorkStartDate)), u.ResignationDate) AS varchar(2)) +' dag '
ELSE
CONVERT(varchar(4), DATEDIFF(dd, WorkStartDate, GETDATE())/365) + ' år '+
CONVERT(varchar(4), DATEDIFF(MONTH, WorkStartDate, GETDATE()) % 12) + ' måneder '+
CAST(DATEDIFF(dd, DATEADD(mm, DATEDIFF(mm, DATEADD(yy, DATEDIFF(yy, WorkStartDate, GETDATE()), WorkStartDate), GETDATE()),
DATEADD(yy, DATEDIFF(yy, WorkStartDate, GETDATE()), WorkStartDate)), GETDATE()) AS varchar(2)) +' dag ' end) as Ancinitet,
(CASE
WHEN u.ResignationDate IS NOT NULL THEN
DATEDIFF(day, WorkStartDate, u.ResignationDate)
ELSE
DATEDIFF(day, WorkStartDate, GETDATE())
end) as AncinitetAntalDag,
p.DepartmentName AS Afdelinger,
E.Name AS Ansættelsesstatus,
u.ResignationDate AS Opsigelsesdato,
(CASE WHEN etq.Id IS NOT NULL THEN t.Name ELSE 'Aktiv' END) AS Terminationreason,
totals.Nr_Employees as TotalEmployees,
SummerCount.Nr_Employees as sumEmployees
FROM
dbo.Paychecks AS p INNER JOIN dbo.Users AS u ON u.Id=p.UserId
INNER JOIN dbo.EmploymentStatuses AS E ON E.Id = u.EmploymentStatusId
LEFT OUTER JOIN dbo.EmployeeTerminationQueue AS etq on etq.UserId = u.Id
LEFT OUTER JOIN dbo.TerminationReasons AS t on t.Id = etq.TerminationReasonid
LEFT JOIN EmployeesCount As totals on totals.DepartmentName = p.DepartmentName
CROSS JOIN
(
SELECT SUM(Nr_Employees) As Nr_Employees
FROM EmployeesCount
) As SummerCount
WHERE u.CustomerId=214 AND u.IsDeleted = 0
AND etq.StartDate >= #EndDateFrom AND etq.StartDate <= #EndDateTo
AND
((#Gender != 'B' AND
#Gender = (CASE WHEN right(rtrim(SSN), 1) IN ('1', '3', '5', '7', '9') THEN 'M'
WHEN right(rtrim(SSN), 1) IN ('2', '4', '6', '8', '0') THEN 'K'
END))
OR
(#Gender = 'B'))
AND
((#TerminationReason != 0 AND #TerminationReason = (CASE WHEN etq.Id IS NOT NULL THEN t.Id ELSE 0 END))
OR
(#TerminationReason = 0))
AND u.EmploymentStatusId = 2
order by p.DepartmentName
Related
I am getting an error near Alias Names i.e., Month_Name, Limit_Mins, Amount in this dynamic sql, how do i resolve that , i tried with adding one more quote, but when i do tyhat i am only getting #columnames into the sql. How do i resolve the error and make it part of the string
DECLARE #columns NVARCHAR(MAX) = '', #sql NVARCHAR(MAX) = '';
SELECT
#columns = coalesce(#columns + ',', '') + quotename(Limit_Mins)
from
(
select DISTINCT
(L.Limit_Mins ) as 'Limit_Mins'
from
Limit L
)
AS lIMITS
SELECT #columns
SET
#sql = 'select * from (
SELECT
month (Sa.[Date]) AS 'Month_Name',
convert(varchar(10),
case
when
S.Limit_Mins = L.Limit_Mins
and S.Childcare_Flag = 1
then
S.Limit_Mins
else
0
end
) as 'Limit_Mins', sum(
case
when
S.Childcare_Flag = 1
and S.Limit_Mins = L.Limit_Mins
then
case
when
D.PID = Sa.PID
and D.Discount_Date = Sa.[Date]
then
D.Discount_Price
else
P.Retail_price
end
*Sa.Quantity
else
0
end
) as 'Amount'
FROM
Limit L
join
Store S
on L.Limit_Mins = S.Limit_Mins
join
Sale Sa
on S.Store_Number = Sa.Store_number
join
[Date] Dt
on Dt.[Date] = Sa.[Date]
join
Product P
on Sa.PID = P.PID
left outer join
Discount D
on Sa.PID = D.PID
and Sa.[Date] = D.Discount_Date
WHERE
Sa.[Date] >= DATEADD(year, - 1, DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1))
AND Sa.[Date] < DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1) -- DATEDIFF(MM,Sale.[Date] ,GETDATE())<=12
--and Sale.[Date] < DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
GROUP BY
month(Sa.[Date]) ,
case
when
S.Limit_Mins = L.Limit_Mins
and S.Childcare_Flag = 1
then
S.Limit_Mins
else
0
end
union all
SELECT
month (Sa.[Date]) AS 'Month_Name',
''No Childcare'' as 'Limit_Mins',
isnull(sum(
case
when
S.Childcare_Flag = 0
then
case
when
D.PID = Sa.PID
and D.Discount_Date = Sa.[Date]
then
D.Discount_Price
else
P.Retail_price
end
*Sa.Quantity
else
0
end
), 0) as 'Sales_Amount'
FROM
Store S
join
Sale Sa
on S.Store_Number = Sa.Store_number
join
[Date] Dt
on Dt.[Date] = Sa.[Date]
join
Product P
on Sa.PID = P.PID
left outer join
Discount D
on Sa.PID = D.PID
and Sa.[Date] = D.Discount_Date
WHERE
Sa.[Date] >= DATEADD(year, - 1, DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1))
AND Sa.[Date] < DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1) -- DATEDIFF(MM,Sale.[Date] ,GETDATE())<=12
--and Sale.[Date] < DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
GROUP BY
month(Sa.[Date])
)
A PIVOT(sum(Amount) for Limit_Mins in
(
'+#columns+
',[No Childcare]
)
)as PIVOTTable
order by
[Month]'
print #sql
Use brackets instead of quotes: month (Sa.[Date]) AS [Month_Name],
I tried the quotes earlier, but it was throwing an error invalid column which i later realized was happening because i renamed the alias and forgot to rename the same column order by , Thanks for the input
If you just create "temp" database the following code can create and add sample data into the tables.
Query is to subtract TOTAL REFUNDS FROM TOTAL SALES which results in a new column named NET TOTAL.
Show: UserID, SiteID, Name, TOTAL Sales, Total Refunds, Net Total
image linked for sample data
Thanks
CREATE TABLE temp.dbo.Users
(
UserID INT,
SiteID INT,
Name VARCHAR(20)
)
CREATE TABLE temp.dbo.TRANSACTIONS
(
TransactionID int,
UserID int,
SiteID int,
TransactionType varchar(10),
TransactionDate Date,
Amount money
)
INSERT INTO temp.dbo.Users
VALUES (1, 1, 'ARTHUR'), (2, 1, 'AARON'), (3, 2, 'BRETT')
INSERT INTO temp.dbo.TRANSACTIONS
VALUES (4, 1, 1, 'SALE', GETDATE(), 120),
(6, 1, 1, 'REFUND', GETDATE(), 120),
(7, 2, 2, 'SALE', GETDATE(), 90),
(9, 2, 1, 'SALE', GETDATE(), 30),
(10, 2, 1, 'SALE', GETDATE(), 30),
(11, 2, 1, 'SALE', GETDATE(), 30),
(12, 2, 1, 'REFUND', GETDATE(), 30)
Query: This is my current query where I have tried to name it using WITH clause but no luck
SELECT
U.UserID, U.SiteID, U.Name,
SUM(CASE WHEN T.TransactionType = 'SALE' THEN T.Amount ELSE 0 END) AS [TOTAL SALES],
SUM(CASE WHEN T.TransactionType = 'REFUND' THEN T.Amount ELSE 0 END) AS [TOTAL REFUNDS]
FROM
temp.dbo.Users AS U
INNER JOIN
temp.dbo.Transactions AS T ON U.UserID = T.UserID AND U.SiteID = T.SiteID
GROUP BY
U.UserID, U.SiteID, U.Name
Welcome to Stack Overflow! Your question is very good, but it would be better if you provided an expected result set along with your sample data and work in progress.
There are a few approaches that will solve your problem:
SUM(CASE WHEN T.TransactionType = 'SALE' THEN T.Amount ELSE 0 END) -
SUM(CASE WHEN T.TransactionType = 'REFUND' THEN T.Amount ELSE 0 END)
AS [NET TOTAL]
or
SUM(CASE
WHEN T.TransactionType = 'SALE' THEN T.Amount
WHEN T.TransactionType = 'REFUND' THEN -1 * T.Amount
ELSE 0
END) AS [NET TOTAL]
This might work
with c as(
SELECT
U.UserID,
COUNT(U.UserID) OVER (PARTITION BY U.UserID) AS cnts,
U.SiteID,
U.Name,
SUM(CASE WHEN T.TransactionType = 'SALE' THEN T.Amount ELSE 0 END) AS [TOTAL SALES],
SUM(CASE WHEN T.TransactionType = 'REFUND' THEN T.Amount ELSE 0 END) AS [TOTAL REFUNDS]
-- SUM(T.Amount) AS [TOTALS]
FROM
temp.dbo.Users AS U
INNER JOIN
temp.dbo.Transactions AS T ON U.UserID = T.UserID AND U.SiteID = T.SiteID
GROUP BY
U.UserID, U.SiteID, U.Name
)
select *
,[NET TOTAL] = [TOTAL SALES] - [TOTAL REFUNDS]
from c
also you can do this
SELECT
U.UserID,
COUNT(U.UserID) OVER (PARTITION BY U.UserID) AS cnts,
U.SiteID,
U.Name,
SUM(CASE WHEN T.TransactionType = 'SALE' THEN T.Amount ELSE 0 END) AS [TOTAL SALES],
SUM(CASE WHEN T.TransactionType = 'REFUND' THEN T.Amount ELSE 0 END) AS [TOTAL REFUNDS],
-- SUM(T.Amount) AS [TOTALS]
SUM(CASE WHEN T.TransactionType = 'SALE' THEN T.Amount ELSE 0 END)
- SUM(CASE WHEN T.TransactionType = 'REFUND' THEN T.Amount ELSE 0 END) as [NET TOTAL]
FROM
temp.dbo.Users AS U
INNER JOIN
temp.dbo.Transactions AS T ON U.UserID = T.UserID AND U.SiteID = T.SiteID
GROUP BY
U.UserID, U.SiteID, U.Name
Hopefully an easy one but I need help.
I have two queries looking at the same data but with different where statements.
The data shows value of different card brands from the days trading. however, each total is on a separate line so id like to see all on one line for a store
so [LOCATION], [TRADE DATE], [VISA],[AMEX],[# RECORDS].
I have limited the query to a single location for now.
Any help would be most appreciated
Query A (Visa records)
SELECT
TILLREADREQUEST.STRTRADECODE AS [LOCATION]
,TILLREADREQUEST.DTMTRADEDATE AS [TRADE DATE]
,SUM(TILLREADDETAIL.CURVALUE) AS [VISA]
,COUNT(TILLREADREQUEST.ctrcode) AS [# RECORDS],
FROM
TILLREADDETAIL INNER JOIN
TILLREADREQUEST ON TILLREADDETAIL.LINTREQUESTCODE = TILLREADREQUEST.CTRCODE
WHERE (TILLREADDETAIL.INTTENDERCODE IN ('3')) and TILLREADREQUEST.DTMTRADEDATE > getdate()-2 AND STRTRADECODE = 'SHEFFIELD'
group by TILLREADREQUEST.STRTRADECODE,TILLREADREQUEST.DTMTRADEDATE*
Query B (Amex Records)
SELECT
TILLREADREQUEST.STRTRADECODE AS [LOCATION]
,TILLREADREQUEST.DTMTRADEDATE AS [TRADE DATE]
,SUM(TILLREADDETAIL.CURVALUE) AS [AMEX]
FROM
TILLREADDETAIL INNER JOIN
TILLREADREQUEST ON TILLREADDETAIL.LINTREQUESTCODE = TILLREADREQUEST.CTRCODE
WHERE (TILLREADDETAIL.INTTENDERCODE IN ('4')) and TILLREADREQUEST.DTMTRADEDATE > getdate()-2 AND STRTRADECODE = 'SHEFFIELD'
group by TILLREADREQUEST.STRTRADECODE,TILLREADREQUEST.DTMTRADEDATE*
Use CASEin your query for the particular condition:
SELECT
TILLREADREQUEST.STRTRADECODE AS [LOCATION]
,TILLREADREQUEST.DTMTRADEDATE AS [TRADE DATE]
,SUM(CASE WHEN TILLREADDETAIL.INTTENDERCODE IN ('3')
THEN TILLREADDETAIL.CURVALUE
ELSE 0
END
) AS [VISA]
,SUM(CASE WHEN TILLREADDETAIL.INTTENDERCODE IN ('4')
THEN TILLREADDETAIL.CURVALUE
ELSE 0
END
) AS [AMEX]
,COUNT(TILLREADREQUEST.ctrcode) AS [# RECORDS],
FROM
TILLREADDETAIL INNER JOIN
TILLREADREQUEST ON TILLREADDETAIL.LINTREQUESTCODE = TILLREADREQUEST.CTRCODE
WHERE (TILLREADDETAIL.INTTENDERCODE IN ('3', '4')) and TILLREADREQUEST.DTMTRADEDATE > getdate()-2 AND STRTRADECODE = 'SHEFFIELD'
group by TILLREADREQUEST.STRTRADECODE,TILLREADREQUEST.DTMTRADEDATE*
If you also want to count records separately for VISA/AMEX then you'll have to add case there as well.
SELECT
TILLREADREQUEST.STRTRADECODE AS [LOCATION]
,TILLREADREQUEST.DTMTRADEDATE AS [TRADE DATE]
,SUM(CASE WHEN TILLREADDETAIL.INTTENDERCODE IN ('3') THEN TILLREADDETAIL.CURVALUE ELSE 0 END) AS [VISA]
,SUM(CASE WHEN TILLREADDETAIL.INTTENDERCODE IN ('4') THEN TILLREADDETAIL.CURVALUE ELSE 0 END) AS [AMEX]
,COUNT(CASE WHEN TILLREADREQUEST.ctrcode = '3' THEN 1 ELSE NULL END) AS [# RECORDS],
,COUNT(CASE WHEN TILLREADREQUEST.ctrcode = '4' THEN 1 ELSE NULL END) AS [# RECORDS]
FROM
TILLREADDETAIL INNER JOIN
TILLREADREQUEST ON TILLREADDETAIL.LINTREQUESTCODE = TILLREADREQUEST.CTRCODE
WHERE (TILLREADDETAIL.INTTENDERCODE IN ('3','4')) and TILLREADREQUEST.DTMTRADEDATE > getdate()-2 AND STRTRADECODE = 'SHEFFIELD'
group by TILLREADREQUEST.STRTRADECODE,TILLREADREQUEST.DTMTRADEDATE*
I need the query to give a summary of different ResourceId, You can see "G1" AND a series of "M0" Resources.
I want this "M0" Resources as "Press shop" in summary with its scheduledqty as sum and G1 as "Grinding".
This is my query:
Select
'' as Detail,
ShiftDate,
Max(ShiftId) as ShiftId,
ResourceId,
ResourceDesc,
LineId,
CellNo,
Item,
ItemDesc,
Sum(ScheduledQty) as ScheduledQty
from (
Select Case When b.Remarks= 'B' and cast(a.PlannedStartTime as Time) <='08:30:00.0000000'
Then Case When datename(dw,cast(a.PlannedStartTime as Date))='Monday'
Then cast(a.PlannedStartTime-2 as Date)
else cast(a.PlannedStartTime-1 as Date) end
Else cast(a.PlannedStartTime as Date)
End as ShiftDate,
b.Remarks as ShiftId,
a.ResourceId,
c.ResourceDesc,
c.LineId,
c.CellNo,
a.RoutingId as Item,
d.ItemDesc,
convert(nvarchar(8),a.PlannedStartTime,114) as StartTime,
convert(nvarchar(8),a.PlannedEndTime,114) as EndTime,
Sum(Round(a.QtyAllocated,0)) as ScheduledQty
From WorkOrderOpResPlan a
Left Join LocationCalendar b On a.PlantId=b.PlantId
and Cast(a.PlannedStartTime as Time)>=Cast(b.ShiftStartTime as Time)
and Cast(a.PlannedEndTime as Time)<=cast(b.ShiftEndTime as Time)
Inner Join ResourceMaster c on a.ResourceId=c.ResourceId
and a.PlantId=c.PlantId and c.ResourceType='Simple'
Left Join ItemMaster d On a.RoutingId=d.Item
and a.PlantId=d.PlantId
Where a.PlantId='SDL'
Group by
b.Remarks,
a.ResourceId,
c.ResourceDesc,
c.LineId,
c.CellNo,
a.RoutingId,
d.ItemDesc,
a.PlannedStartTime,
a.PlannedEndTime)x
Where ShiftDate<=Cast(GetDate()+2 as Date)
Group by ShiftDate, ResourceId, ResourceDesc, LineId, CellNo, Item, ItemDesc
I want to get the scheduledQty to be summarized based on the differrent ResourceId. Please Help Me
This is the image 1
Try this please. Please note that to reduce the number of rows you have to decide which column values are not needed (like Item and Item Description).
SELECT
'' AS Detail
, ShiftDate
, MAX(ShiftId) AS ShiftId
, ResourceId
, ResourceDesc
, LineId
, CellNo
, SUM(ScheduledQty) AS ScheduledQty
FROM (
SELECT
CASE
WHEN b.Remarks = 'B' AND
CAST(a.PlannedStartTime AS time) <= '08:30:00.0000000' THEN CASE
WHEN DATENAME(dw, CAST(a.PlannedStartTime AS date)) = 'Monday' THEN CAST(a.PlannedStartTime - 2 AS date)
ELSE CAST(a.PlannedStartTime - 1 AS date)
END
ELSE CAST(a.PlannedStartTime AS date)
END AS ShiftDate
, b.Remarks AS ShiftId
, a.ResourceId
, CASE
WHEN a.ResourceId = 'M0' THEN 'Press shop'
WHEN a.ResourceId = 'G1' THEN 'Grinding'
ELSE c.ResourceDesc
END AS ResourceDesc
, c.LineId
, c.CellNo
, a.RoutingId AS Item
, SUM(ROUND(a.QtyAllocated, 0)) AS ScheduledQty
FROM WorkOrderOpResPlan a
LEFT JOIN LocationCalendar b ON a.PlantId = b.PlantId
AND CAST(a.PlannedStartTime AS time) >= CAST(b.ShiftStartTime AS time)
AND CAST(a.PlannedEndTime AS time) <= CAST(b.ShiftEndTime AS time)
INNER JOIN ResourceMaster c ON a.ResourceId = c.ResourceId
AND a.PlantId = c.PlantId
AND c.ResourceType = 'Simple'
LEFT JOIN ItemMaster d ON a.RoutingId = d.Item
AND a.PlantId = d.PlantId
WHERE a.PlantId = 'SDL'
GROUP BY
b.Remarks
, a.ResourceId
, CASE
WHEN a.ResourceId = 'M0' THEN 'Press shop'
WHEN a.ResourceId = 'G1' THEN 'Grinding'
ELSE c.ResourceDesc
END
, c.LineId
, c.CellNo
, a.RoutingId
) x
WHERE ShiftDate <= CAST(GETDATE() + 2 AS date)
GROUP BY
ShiftDate
, ResourceId
, ResourceDesc
, LineId
, CellNo
Is it possible to get CreatedDateTime and Createdby for the security role added to the user through sql query
This is query used to get the Security role
select distinct a.id as username , a.NAME Name, f.Text [Role]
from userinfo a (nolock) join securityuserrole b (nolock) on a.id=b.user_
join SECURITYUSERROLECONDITION c (nolock) on b.recid = c.securityuserrole
join [Dynamics_STG_model].[dbo].[ModelSecurityRole] e (nolock) on e.rolehandle = b.securityrole
join [Dynamics_STG_model].[dbo].[ModelElementLabel] f (nolock) on e.LABELID = f.LabelId and e.LABELMODULE = f.Module and f.Language='en_us'
Please help me regarding this.
Thanks in Advance!
I figured out the answer by myself:
Declare #StartDate datetime
Declare #EndDate datetime
Set #StartDate = '2015-07-07 01:31:38.000'
Set #EndDate = '2015-08-21 01:14:14.000'
Set #StartDate = convert(datetime, dateadd(hour, 7, #StartDate), 100)
Set #EndDate = convert(datetime, dateadd(hour, 7, #EndDate), 100)
select distinct a.NAME [User Name]
,b.USERNAME [Role Modified By]
,convert(datetime, dateadd(hour, -7, b.CREATEDDATETIME), 100) [Modified DateTime]
,case b.LOGTYPE
when 0 then 'Added'
when 1 then 'Removed'
end as Status
,d.Text Role
from USERINFO a (nolock)
join(
select (case when logtype = 0 then dbo.CONPEEK(CAST(dbo.CONPEEK(data, 16) AS varbinary(8000)), 2)
when logtype = 1 then dbo.CONPEEK(CAST(dbo.CONPEEK(data, 10) AS varbinary(8000)), 2)
end) AS UserNam
,USERNAME
,CREATEDDATETIME
,logtype
,(case when logtype = 0 then dbo.CONPEEK(CAST(dbo.CONPEEK(data, 15) AS varbinary(8000)), 2)
when logtype = 1 then dbo.CONPEEK(CAST(dbo.CONPEEK(data, 9) AS varbinary(8000)), 2)
end) as SecurityRole
from SYSDATABASELOG (nolock) where TABLE_=65492 and data !='') b
on a.id = b.UserNam
left outer join [DynamicsAX_model].[dbo].[modelsecurityrole] c (nolock) on b.SecurityRole =c.rolehandle
join [modelelementlabel] d (nolock) on c.labelid = d.labelid
and c.LABELMODULE = d.module
and d.Language='en_us'
where b.CREATEDDATETIME >= #StartDate and b.CREATEDDATETIME <=#EndDate order by [Modified DateTime] desc
Conpeek and consize are two functions we need to create from the below link download ConPeek.sql and ConSize.sql
You can try using database logging for table SecurityUserRole (System → Security user role).