In my project, the customers of the company are calling to make requests about their equipment. Everytime a call is made, it's saved in database. Now I need to know how many calls did the company get every month of a specific year so I've written that request :
SELECT COUNT(EveLngId) FROM T_Evenement
where EveLngDosId = 1062
And EveLngBibId = 268
And EveTinSite = 1
And EveLngEleId <> 17432
And (EveTinParEmail is null OR EveTinParEmail = 0)
And (EveLngTicketTransfertId IS NULL OR EveLngTicketTransfertId = 0)
And (EveTinIncidentAnnulation is null or EveTinIncidentAnnulation=0)
And YEAR(EveDatRedaction) = 2013
group by MONTH(EveDatRedaction)
The request works but the thing is that when the value for a month is null, i doesn't display Null or 0 but it skips it. To manage that, I create a Calendar table as below:
So now I need to join these two tables to have the value for each month but I can figure out how to do that. Any advise or solution ?
;WITH ResultsCTE AS
(
SELECT MONTH(EveDatRedaction) AS ResultMonth,
COUNT(EveLngId) AS ResultCount
FROM T_Evenement
where EveLngDosId = 1062
And EveLngBibId = 268
And EveTinSite = 1
And EveLngEleId <> 17432
And (EveTinParEmail is null OR EveTinParEmail = 0)
And (EveLngTicketTransfertId IS NULL OR EveLngTicketTransfertId = 0)
And (EveTinIncidentAnnulation is null or EveTinIncidentAnnulation=0)
And YEAR(EveDatRedaction) = 2013
GROUP BY MONTH(EveDatRedaction)
)
SELECT CalendarStrLibelle,ISNULL(ResultCount,0) AS ResultCount
FROM Calendar
LEFT JOIN ResultsCTE
ON ResultMonth = CalendarLngId
Try this one -
SELECT CalendarStrLibelle
, ResultCount = ISNULL(cnt, 0)
FROM dbo.Calendar c
LEFT JOIN (
SELECT
[month] = MONTH(EveDatRedaction)
, cnt = COUNT(EveLngId)
FROM dbo.T_Evenement
WHERE EveLngDosId = 1062
AND EveLngBibId = 268
AND EveTinSite = 1
AND EveLngEleId <> 17432
AND ISNULL(EveTinParEmail, 0) = 0
AND ISNULL(EveLngTicketTransfertId, 0) = 0
AND ISNULL(EveTinIncidentAnnulation, 0) = 0
AND YEAR(EveDatRedaction) = 2013
GROUP BY MONTH(EveDatRedaction)
) t ON t.[month] = c.CalendarLngId
Related
I need some help mimicking a TFS query.
I have tried writing the following SQL query to do so but I am not able to get a matching population:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb.dbo.#LastRecord') IS NOT NULL DROP TABLE #LastRecord
SELECT System_Id
, LastUpdatedDateTime = MAX(LastUpdatedDateTime)
INTO #LastRecord
FROM [dimWorkItem]
GROUP BY System_Id
SELECT distinct ID = w.System_Id
--Cannot find Department
, Department = '?'
, w.TeamProjectSK
, RequestedByUser = w.Custom_RequestedBy
, Title = w.System_Title
, [Priority] = w.Microsoft_VSTS_Common_Priority
, Activity = w.Microsoft_VSTS_Common_Activity
, da.AreaPath
, [State] = w.System_State
, Reason = w.System_Reason
, ClosedDate = w.Microsoft_VSTS_Common_ClosedDate
, ActivatedDate = Microsoft_VSTS_Common_ActivatedDate
, DevHours = Custom_DevHours
, CreatedDate = w.System_CreatedDate
, AssignedTo = dp.Name
, [Week] = CASE WHEN (w.System_State = 'Active' OR Microsoft_VSTS_Common_ClosedDate >= dateadd(d,-7,CONVERT(Date,getdate(),1))) THEN 'Current'
WHEN (w.System_State = 'Active' OR Microsoft_VSTS_Common_ClosedDate >= dateadd(d,-14,CONVERT(Date,getdate(),1)) AND Microsoft_VSTS_Common_ClosedDate < dateadd(d,-7,CONVERT(Date,getdate(),1))) THEN 'Last'
ELSE 'Previous' END
, TSRNumber = Custom_TSRNumber
FROM
(Select * from (select *, rn = row_number() over(partition by w1.System_Id, w1.TeamProjectSK, w1.System_State order by w1.System_Rev desc)
from dbo.DimWorkItem w1) d where rn = 1) w
JOIN #LastRecord l ON w.System_Id = l.System_Id AND w.LastUpdatedDateTime = l.LastUpdatedDateTime
LEFT OUTER JOIN dbo.DimArea da ON w.AreaSK = da.AreaSK
LEFT OUTER JOIN DimPerson dp ON w.System_AssignedTo__PersonSK = dp.PersonSK
WHERE System_WorkItemType = 'Task'
AND da.AreaPath like '\LOS\Reporting%'
AND w.Microsoft_VSTS_Common_Priority < 4
Also if anyone knows where I could find the department field as I am not sure whether it is a custom field or not.
SQL Server 2014: 12.0
TFS: 12.0
Visual studio professional 2015: 14.0
Thank you in advance for your suggestions!
I found a solution although still not able to find the the Department field :
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
IF OBJECT_ID('tempdb.dbo.#LastRecord') IS NOT NULL DROP TABLE #LastRecord
SELECT System_Id, LastChangedDate = MAX(System_ChangedDate)
INTO #LastRecord
FROM [dimWorkItem]
GROUP BY System_Id
DECLARE #FromDateWeek DATE
DECLARE #FromDateTwoWeek DATE
SET #FromDateWeek = dateadd(d,-7,CONVERT(Date,getdate(),1))
SET #FromDateTwoWeek = dateadd(d,-14,CONVERT(Date,getdate(),1))
--SELECT #FromDate
SELECT ID = w.System_Id
--Cannot find Department
, Department = '?'
, w.TeamProjectSK
, RequestedByUser = w.Custom_RequestedBy
, Title = w.System_Title
, [Priority] = w.Microsoft_VSTS_Common_Priority
, Activity = w.Microsoft_VSTS_Common_Activity
, da.AreaPath
, [State] = w.System_State
, Reason = w.System_Reason
, ClosedDate = w.Microsoft_VSTS_Common_ClosedDate
, ActivatedDate = Microsoft_VSTS_Common_ActivatedDate
, DevHours = Custom_DevHours
, CreatedDate = w.System_CreatedDate
, AssignedTo = dp.Name
, [Week] = CASE WHEN w.Microsoft_VSTS_Common_ClosedDate >= #FromDateWeek OR w.System_State = 'Active' THEN 'Current'
WHEN (w.Microsoft_VSTS_Common_ClosedDate >= #FromDateTwoWeek AND w.Microsoft_VSTS_Common_ClosedDate < #FromDateWeek)
OR w.Microsoft_VSTS_Common_ClosedDate < #FromDateWeek THEN 'Last'
ELSE 'Previous' END
FROM [dimWorkItem] w
JOIN #LastRecord l ON w.System_Id = l.System_Id AND w.System_ChangedDate = l.LastChangedDate
LEFT OUTER JOIN DimPerson dp ON w.System_AssignedTo__PersonSK = dp.PersonSK
LEFT OUTER JOIN dbo.DimArea da ON w.AreaSK = da.AreaSK
WHERE
da.AreaPath LIKE '\LOS\Reporting%'
AND System_WorkItemType = 'Task'
AND (Microsoft_VSTS_Common_ClosedDate >= #FromDateTwoWeek
OR w.System_State = 'Active')
AND ISNULL(Microsoft_VSTS_Common_Priority,0) < 4
AND w.System_Reason <> 'Obsolete'
i want to update my records, if the day of the last payment of the client its greater than 100;
update clients set ind_mo = 2,
ind_pay=2
if its less than 100;
update clients set ind_mo = 1,
ind_pay = 1
if the the own of the client its = 0
update clients set ind_mo = 1,
ind_pay = 1
i already tried this but it does not update my record if the own its 0
if (datediff(day,((select top 1 fec_ven from
cxc_cuedoc cue inner join cxc_cliente cli
on cli.cod_cli = cue.cod_cli where sal_doc !=0 and cue.tip_doc = '010' and num_doc=cue.num_doc)),getdate())) > 110
update cxc_cliente
set ind_mora ='2',
IND_JURIDICO = '2';
else
update cxc_cliente
set ind_mora = '1',
ind_juridico ='1'
UPDATE Cli
SET Cli.ind_mo = CASE WHEN DATEDIFF(DAY , fec_ven , GETDATE()) > 100
THEN 2 ELSE 1 END
,Cli.ind_pay = CASE WHEN DATEDIFF(DAY , fec_ven , GETDATE()) > 100
THEN 2 ELSE 1 END
from cxc_cuedoc cue
inner join cxc_cliente cli on cli.cod_cli = cue.cod_cli
and cli.num_doc = cue.num_doc
where sal_doc != 0
and cue.tip_doc = '010'
Or if you are only interested in the last row, maybe something like this...
WITH X AS (
SELECT ind_mo , ind_pay , fec_ven
, ROW_NUMBER() OVER (PARTITION BY cli.cod_cli ORDER BY fec_ven DESC) rn
FROM cxc_cuedoc cue
inner join cxc_cliente cli on cli.cod_cli = cue.cod_cli
and cli.num_doc = cue.num_doc
where sal_doc !=0
and cue.tip_doc = '010'
)
UPDATE x
SET x.ind_mo = CASE WHEN DATEDIFF(DAY , x.fec_ven , GETDATE()) > 100
THEN 2 ELSE 1 END
,x.ind_pay = CASE WHEN DATEDIFF(DAY , x.fec_ven , GETDATE()) > 100
THEN 2 ELSE 1 END
WHERE x.rn = 1
i have an sp that i check if user's password change date has 14 days
left(flag=0) and i send email to that users and i that sp i check(by a
col.flag) if email already sent or not.after that i update the the
flag col.in an another SP(ExpiryNotificationFlag) to 1 of users list whose email has
already sent..now i don't know how to check for 7,3,2,1 days as flag
col value is already 1 ?
sp
SELECT TenantName
, TenantEmail
, GMAP_code
, ContactID FROM (
SELECT b_1.TenantName
, b_1.TenantEmail
, LastPDWChangeDate =(SELECT ISNULL(max (DateChanged),GETDATE()) FROM dbo.wsm_Contact_PwdHistory WHERE ContactID = b_1.TenantRegContactID)
, ExpiryNotificationFlag =(SELECT top 1 ExpiryNotificationFlag FROM dbo.wsm_Contact_PwdHistory WHERE ContactID = b_1.TenantRegContactID order by DateChanged desc)
, GMAP_code =(SELECT TOP 1 ISNULL(GMAP_CODE,'') from wsm_Ref_Buildings where BuildingId = b_1.BuildingID)
, b_1.TenantRegContactID as ContactID
FROM dbo.wsm_Contact AS a LEFT OUTER JOIN
(
SELECT C.Name AS TenantName
, A.SiteID
, A.BuildingID
, A.FloorID
, A.ContactID AS TenantRegContactID
, D.LEASID
, C.Phone AS TenantPhone
, C.Email AS TenantEmail
, B.UserID AS userid
, C.Mobile AS TenantMobile
, B.UserType
FROM dbo.wsm_Contact_Tenancy AS A
INNER JOIN dbo.wsm_Contact_User AS B ON A.ContactID = B.ContactID AND B.Active = 1
INNER JOIN dbo.wsm_Contact AS C ON B.ContactID = C.ContactID
INNER JOIN (
SELECT DISTINCT COALESCE (LEASID, ExtLeasNum) AS LEASID
, SiteID
, BuildingID
, FloorID
FROM dbo.wsm_Contact) AS D ON A.SiteID = D.SiteID AND A.BuildingID = D.BuildingID AND A.FloorID = D.FloorID) AS b_1 ON
COALESCE (a.LEASID, a.ExtLeasNum) = b_1.LEASID AND a.SiteID = b_1.SiteID AND a.BuildingID = b_1.BuildingID AND a.FloorID = b_1.FloorID
INNER JOIN dbo.wsm_Ref_Floors AS C ON a.FloorID = C.FloorId
WHERE (a.OCCPSTAT NOT IN ('I', 'P')) and C.Deleted = 0 and b_1.userid is not null ) AS A WHERE DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 76 AND ISNULL(ExpiryNotificationFlag,0) <> 1
END
update Query
UPDATE dbo.wsm_Contact_PwdHistory set ExpiryNotificationFlag = 1 WHERE ContactID = #ContactID
you can do it like that
( (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 76 AND ISNULL(ExpiryNotificationFlag,0) = 0) --14 days
or (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 83 AND ISNULL(ExpiryNotificationFlag,0) = 1) --7days
or (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 87 AND ISNULL(ExpiryNotificationFlag,0) = 2) --3 days
or (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 88 AND ISNULL(ExpiryNotificationFlag,0) = 3) --2 days
or (DATEDIFF(DAY,A.LastPDWChangeDate,getdate()) = 89 AND ISNULL(ExpiryNotificationFlag,0) = 4) --1 day
)
for that u have to modify Expiry notification flag to int instead of a Boolean
after that make a SP where will u update the value from
0 to 1,1 to 2,2 to 3 etc.
Youre essentially making the following complaint:
"A boolean datatype can only store one of two values!"
Indeed, so swap out that flag for a "Number of Days Left" column, and compare it to 14, 7, whatever....
Note, ExpiryNotificationFlag column isn't a great name - how about "PasswordExpiryEmailSent"
Sometimes these problems get a lot easier to think about when the columns have better names
We want to create a data-set which shows the monthly average count in our equipment table broken down by it's status: Active, Scrapped, New.
The more I ponder this it seems that the only way to accomplish this is to first create a container temp table and evaluate each record using a cursor.
Can this be accomplished without a temp table?
The following just shows the fields we're working with:
SELECT a1.statusdate, a1.CreateDate,
RunningTotalActive = count([status]='Active'),
RunningTotalScrapped = count([status]='Scrapped'),
NewEquipment = count(Month(a1.CreateDate) )
FROM dbo.Equipment AS a1
INNER JOIN dbo.Equipment AS a2
ON a2.statusdate <= a1.CreateDate
GROUP BY a1.statusdate
ORDER BY a1.statusdate desc
I'm making a few SWAGs about your data, but the idea is to average the sums over simple counts by month; using CTEs.
; WITH A AS (
SELECT a1.statusdate,
Active = CASE a1.[status] WHEN 'Active' THEN 1 ELSE 0 END,
Scrapped = CASE a1.[status] WHEN 'Scrapped' THEN 1 ELSE 0 END,
New = CASE WHEN a2.statusdate = a1.CreateDate THEN 1 ELSE 0 END --Guessing here that "new" means status date and create date are the same
FROM dbo.Equipment AS a1
INNER JOIN dbo.Equipment AS a2
ON a2.statusdate <= a1.CreateDate --"status" can be older than "create" for a piece of equipment? Not sure I understand this criteria. May need sample data.
), B AS (
SELECT Y = DATEPART(YEAR, statusdate)
, M = DATEPART(MONTH, statusdate)
, SumActive = SUM(Active)
, SumScrapped = SUM(Scrapped)
, SumNew = SUM(New)
FROM A
GROUP BY DATEPART(YEAR, statusdate), DATEPART(MONTH, statusdate)
)
SELECT Y, M,
RunningTotalActive = AVG(SumActive)OVER(PARTITION BY Y,M ORDER BY Y,M),
RunningTotalScrapped = AVG(SumScrapped)OVER(PARTITION BY Y,M ORDER BY Y,M),
NewEquipment = AVG(SumNew)OVER(PARTITION BY Y,M ORDER BY Y,M)
FROM B;
Can you show some sample data?
I had modified your script following my understanding. Can you try it?
SELECT YEAR(a1.statusdate) AS yr,MONTH(a1.statusdate) AS mon,
RunningTotalActive = count(CASE WHEN a1.[status]='Active' THEN 1 ELSE NULL END ), -- or SUM(CASE WHEN [status]='Active' THEN 1 ELSE 0 END ),
RunningTotalScrapped = count(CASE WHEN a1.[status]='Scrapped' THEN 1 ELSE NULL END),
NewEquipment = count(CASE WHEN YEAR(a1.CreateDate)*12+ MONTH(a1.CreateDate)= YEAR(a1.statusdate)*12+ MONTH(a1.statusdate)) THEN 1 ELSE NULL END )
FROM dbo.Equipment AS a1
GROUP BY YEAR(a1.statusdate),MONTH(a1.statusdate)
ORDER BY YEAR(a1.statusdate),MONTH(a1.statusdate) DESC
In my context, customers are making request and that request are saved in database. For each month, i would like to count the number of requests for each month, so I've tried that :
Select COUNT(EveLngId) as NbreIncidentPrisEnDirect
FROM T_Evenement as TE inner join T_Historique on HisLngEveId = EveLngId, T_Param as TPA
WHERE EveLngDosId = 1062
And EveLngBibId = 268
And HisLngBibId = 267
And ParStrIndex = 'RES'
And TE.EveLngResponsableId = TPA.ParLngId
And EveDatRedaction = EveDatRealisation
And year(EveDatRedaction) = '2013'
group by MONTH(EveDatRedaction)
And I get that result :
So as you see, for that year (2013) I don't have the values for each month, Why ? Because for some of them, the value is 0. There is a way to display the value for each month even if the value is 0 ?
The best solution would be to create a calendar table and JOIN your data. Otherwise, you will need to create a table:
SELECT 1 AS month, 2013 AS year
UNION ALL
SELECT 2, 2013
UNION ALL
SELECT 3, 2013
UNION ALL
SELECT 4, 2013
...
and JOIN it with your query.
Assuming that you have some data for each month (although not matching the where clause), you can use conditional aggregation:
Select sum(case when EveLngDosId = 106 And EveLngBibId = 268 And HisLngBibId = 267
And ParStrIndex = 'RES' And
And EveDatRedaction = EveDatRealisation
then 1 else 0
end) as NbreIncidentPrisEnDirect
FROM T_Evenement as TE inner join
T_Historique
on HisLngEveId = EveLngId join
T_Param as TPA
on TE.EveLngResponsableId = TPA.ParLngId
WHERE year(EveDatRedaction) = '2013'
group by MONTH(EveDatRedaction);
The disadvantage is that this will not use indexes for the where clause.