Count Like Description column and sum based on equipment - sql-server

In SQL Server, I am trying to group equipment and then count the 'like' Descriptions to get the occurrences. Has anyone done anything like that?
Select
Equip, Count like Description,
from
WorkOrder (nolock)
where
DateTm Between DATEADD(month, DATEDIFF(month, 0, getDate()), 0) and DATEADD(month, DATEDIFF(month, -1, getDate()), -1)
Group by
Equip, Description
order by
Equip Asc

This should work. If you want to search with list of descriptions, then add the where class with description like.
Select Equip,Description, count(*) as Count,
from WorkOrder (nolock)
where DateTm Between DATEADD(month, DATEDIFF(month, 0, getDate()), 0) and
DATEADD(month, DATEDIFF(month, -1, getDate()), -1)
Group by Equip,Description order by Equip Asc

I think what you are trying to do is to get those with same description per Equip. You can group by and having clause for this requirement.
select description
, Equip
, count(Equip)
from WorkOrder (nolock)
where DateTm Between dateadd(month, DATEDIFF(month, 0, getDate()), 0)
and dateadd(month, DATEDIFF(month, -1, getDate()), -1)
group by description, Equip
having count(description) > 1

WITH cte
AS (SELECT equip,
description,
CASE
WHEN description LIKE '%part was struck%'
OR description LIKE '%Struck part%' THEN 'STRUCK PART'
WHEN description LIKE '%FAILURE%' THEN 'FAILURE'
ELSE 'RANDOM'
END AS DESCRIPTION_GROUP
FROM workorder (nolock)
WHERE datetm BETWEEN Dateadd(month, Datediff(month, 0, Getdate()), 0)
AND
Dateadd(month, Datediff(month, -1,
Getdate()),
-1
))
SELECT equip,
description_group,
Count(*)
FROM cte
GROUP BY equip,
description_group
ORDER BY equip ASC

Related

SQL Server update caused Datediff to not work

I know there were several articles about this topic already and I went through them but I still am not able to get this to run properly. I also used DATEDIFF_BIG, but then I get this error:
DATEDIFF_BIG is not a recognized built-in function name.
This used to be able to run but I think there was a SQL server update and now all of the TAT queries are breaking.
SELECT
MSTR.FIRST_OF_MTH AS [MONTH],
COALESCE(R.[AREA],T.[AREA]) AS [AREA],
COALESCE(R.NUM_REQUESTS,0) AS NUM_REQUESTS,
COALESCE(R.DURATION_REQ,0) AS DURATION_REQ,
COALESCE(T.NUM_TRANS,0) AS NUM_TRANS,
COALESCE(T.DURATION_TRANS,0) AS DURATION_TRANS
FROM
(
SELECT FIRST_OF_MTH
FROM [EPICDW].[DBO].[DATE_EXT]
WHERE (YEAR([DATE_EXT].[THEDATE]) BETWEEN YEAR(GETDATE()) - 1 AND YEAR(GETDATE()))
GROUP BY FIRST_OF_MTH
) MSTR
LEFT JOIN
(
--transactions
SELECT
DATEADD(month, DATEDIFF(month, 0, [CLOSE_DT]), 0) AS [MONTH],
[TEAM] AS AREA,
SUM(1) AS NUM_TRANS,
SUM(B.[Calendar_Duration]) AS DURATION_TRANS
FROM [dbo].[v_tab_config_bl_trans_comb]
CROSS APPLY fn_Ben_Ops_Turnaround ([OPEN_DT], [CLOSE_DT]) B
WHERE Year([CLOSE_DT]) BETWEEN YEAR(GETDATE()) - 1 AND YEAR(GETDATE())
GROUP BY
DATEADD(month, DATEDIFF(month, 0, [CLOSE_DT]), 0),
[TEAM]
) T
ON MSTR.FIRST_OF_MTH = T.[MONTH]
LEFT JOIN
(
--requests
SELECT
DATEADD(month, DATEDIFF(month, 0, [CLOSED_DT]), 0) AS [MONTH],
TEAM AS AREA,
SUM(1) AS NUM_REQUESTS,
SUM([DUR_CAL]) AS DURATION_REQ
FROM [dbo].[v_tab_config_requests]
WHERE year([CLOSED_DT]) BETWEEN YEAR(GETDATE()) - 1 AND YEAR(GETDATE())
GROUP BY DATEADD(month, DATEDIFF(month, 0, [CLOSED_DT]), 0), TEAM
) R
ON MSTR.FIRST_OF_MTH = R.[MONTH]
AND T.AREA = R.AREA

how to add columns side by side in sql server by using select query

i want to show the select query output in a columns side by side. currently im showing in one column in multiple records.
code
select sum(Fan1Hrs) as Fan1Hrs from (select CONVERT(Date, devicetimestamp) as Date, max(Convert(int, Fan1Hrs)) as Fan1Hrs from RawData where MONTH(DeviceTimeStamp) = MONTH(dateadd(dd, -1, GetDate())) AND YEAR(DeviceTimeStamp) = YEAR(dateadd(dd, -1, GetDate())) group by CONVERT(Date, devicetimestamp))comp1
union all
select sum(Fan2Hrs) as Fan2Hrs from (select CONVERT(Date, devicetimestamp) as Date, max(Convert(int, Fan2Hrs)) as Fan2Hrs from RawData where MONTH(DeviceTimeStamp) = MONTH(dateadd(dd, -1, GetDate())) AND YEAR(DeviceTimeStamp) = YEAR(dateadd(dd, -1, GetDate())) group by CONVERT(Date, devicetimestamp))comp2
union all
select sum(Fan3Hrs) as Fan3Hrs from (select CONVERT(Date, devicetimestamp) as Date, max(Convert(int, Fan3Hrs)) as Fan3Hrs from RawData where MONTH(DeviceTimeStamp) = MONTH(dateadd(dd, -1, GetDate())) AND YEAR(DeviceTimeStamp) = YEAR(dateadd(dd, -1, GetDate())) group by CONVERT(Date, devicetimestamp))comp3
Exp Op:
FAN1Hrs FAN2Hrs FAN3Hrs
1234 1123 2323
Current OP
FAN1Hrs
1234
1123
2323
I think you're looking for something like this
with fan_cte as (
select CONVERT(Date, devicetimestamp) as Date,
max(Convert(int, Fan1Hrs)) as Fan1Hrs,
max(Convert(int, Fan2Hrs)) as Fan2Hrs,
max(Convert(int, Fan3Hrs)) as Fan3Hrs
from RawData
where MONTH(DeviceTimeStamp) = MONTH(dateadd(dd, -1, GetDate()))
AND YEAR(DeviceTimeStamp) = YEAR(dateadd(dd, -1, GetDate()))
group by CONVERT(Date, devicetimestamp))
select sum(Fan1Hrs) as Fan1Hrs, sum(Fan2Hrs) as Fan2Hrs, sum(Fan3Hrs) as Fan3Hrs
from fan_cte;
SteveC's answer may very well be superior, but I wanted to offer an alternative.
Since you are only returning one value due to the MAX() function I don't think you need to SUM() as well. Also the usage of MAX() will ensure only one value per subquery. Given that we can use a CROSS JOIN to give you the side by side results. This will do a Cartesian product (all combinations of all rows), but this won't be a problem since each subquery will only have one row.
SELECT
comp1.Fan1Hrs
, comp2.Fan2Hrs
, comp3.Fan3Hrs
FROM (
SELECT
CONVERT(DATE, devicetimestamp) AS Date
, MAX(CONVERT(INT, Fan1Hrs)) AS Fan1Hrs
FROM RawData
WHERE MONTH(DeviceTimeStamp) = MONTH(DATEADD(dd, -1, GETDATE()))
AND YEAR(DeviceTimeStamp) = YEAR(DATEADD(dd, -1, GETDATE()))
GROUP BY CONVERT(DATE, devicetimestamp)
) comp1
CROSS JOIN (
SELECT
CONVERT(DATE, devicetimestamp) AS Date
, MAX(CONVERT(INT, Fan2Hrs)) AS Fan2Hrs
FROM RawData
WHERE MONTH(DeviceTimeStamp) = MONTH(DATEADD(dd, -1, GETDATE()))
AND YEAR(DeviceTimeStamp) = YEAR(DATEADD(dd, -1, GETDATE()))
GROUP BY CONVERT(DATE, devicetimestamp)
) comp2
CROSS JOIN (
SELECT
CONVERT(DATE, devicetimestamp) AS Date
, MAX(CONVERT(INT, Fan3Hrs)) AS Fan3Hrs
FROM RawData
WHERE MONTH(DeviceTimeStamp) = MONTH(DATEADD(dd, -1, GETDATE()))
AND YEAR(DeviceTimeStamp) = YEAR(DATEADD(dd, -1, GETDATE()))
GROUP BY CONVERT(DATE, devicetimestamp)
) comp3;

Divide results of two queries and obtain result in third query

I have two SQL queries that I want to divide. On their own each query works, and I want to divide their results and obtain into third variable, but I am unsure how.
This query calculate no of cancelled members
(select count(*) as No_of_Member_Cancelled, M.HomeBranch,M.LocationName from
AX.Memberships M
where M.ActiveEnd between DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1,
0) and DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) ,-1)
group by M.HomeBranch,M.LocationName) as g1
This query calculate the no of live members
(select count(*)as No_of_Live_Member , M.HomeBranch,M.LocationName
from AX.Memberships M
where M.ActiveStart between DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) -
1, 0) and DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) ,-1)
group by M.HomeBranch,M.LocationName) as g2
We obtain results like this
if x = g1/g2
x , LocationName , HomeBranch in one table
Best to change those to temp tables then you can do it like this:
select No_of_Member_Cancelled / No_of_Live_Member as x, HomeBranch, LocationName
from G1
join G2 on g1.HomeBranch = g2.HomeBranch and g1.LocationName = g2.LocationName
group by HomeBranch, LocationName
Try this...
SELECT CAST (g1.no_of_member_cancelled AS DECIMAL(10, 2)) /
CAST (g2.no_of_live_member AS DECIMAL(10, 2)) AS x,
g1.homebranch,
g1.locationname
FROM (SELECT Count(*) AS No_of_Member_Cancelled,
M.homebranch,
M.locationname
FROM ax.memberships M
WHERE M.activeend BETWEEN Dateadd(month, Datediff(month, 0, Getdate())
- 1, 0)
AND
Dateadd(month, Datediff(month, 0,
Getdate())
, -1)
GROUP BY M.homebranch,
M.locationname) AS g1
INNER JOIN (SELECT Count(*)AS No_of_Live_Member,
M.homebranch,
M.locationname
FROM ax.memberships M
WHERE M.activestart BETWEEN Dateadd(month, Datediff(month, 0
,
Getdate()) - 1,
0) AND
Dateadd(month, Datediff(month,
0, Getdate(
)), -1)
GROUP BY M.homebranch,
M.locationname) AS g2
ON g1.homebranch = g2.homebranch
AND g1.locationname = g2.locationname
You will need to cast (or convert) your number of cancelled and live members to the datatype that fits your situation given the size of your potential values. You probably should take precaution so you don't get a division by zero error.
SELECT distinct CAST (g1.no_of_member_cancelled AS DECIMAL(10, 2)) /
CAST (g2.no_of_live_member AS DECIMAL(10, 2)) AS x,
g1.homebranch,
g1.locationname,
g1.month,
g1.year
FROM (SELECT Count(*) AS No_of_Member_Cancelled,
M.homebranch,
M.locationname,
month(M.ActiveStart) month,
YEAR(M.ActiveStart) year
FROM ax.memberships M
WHERE M.activeend BETWEEN Dateadd(year, Datediff(year, 0, Getdate()) - 2, 0)
AND
Dateadd(year, Datediff(year, 0, Getdate()), -1)
GROUP BY M.homebranch,
M.locationname,month(M.ActiveStart),
year(M.ActiveStart)) AS g1
INNER JOIN (SELECT Count(*)AS No_of_Live_Member,
M.homebranch,
M.locationname,
month(M.ActiveStart) month,
YEAR(M.ActiveStart) year
FROM ax.memberships M
WHERE M.activestart BETWEEN Dateadd(year, Datediff(year, 0, Getdate()) - 2, 0)
AND
Dateadd(year, Datediff(year, 0, Getdate()), -1)
GROUP BY M.homebranch,
M.locationname,
month(M.ActiveStart),
year(M.ActiveStart)
) AS g2
ON g1.homebranch = g2.homebranch
AND g1.locationname = g2.locationname
AND g1.month = g2.month
AND g1.year = g2.year
Order by g1.year,g1.month
Can you please check my query is right or not. Because I wanted to get from last 2 yrs.

Incorrect syntax near the keyword 'DECLARE' in view

Can someone please confirm how to get rid of the following error.
DECLARE #StartDate DATETIME, #EndDate DATETIME
SET #StartDate = DATEADD(mm, DATEDIFF(mm, 0, getdate()) - 1, 0)
SET #EndDate = DATEADD(mm, 1, #StartDate)
SELECT
dbo.General_Ledger_Detail.Accounting_ID,
dbo.General_Ledger_Detail.Cost_Centre,
dbo.General_Ledger_Detail.Product_ID,
dbo.General_Ledger_Detail.Accounted_Amount AS Amount,
dbo.General_Ledger_Detail.Account_Name,
dbo.General_Ledger_Detail.Accounting_Date,
dbo.Account_Codes_Sales_OPEX$.[Opex Type],
dbo.LogSolOpexCC.Logistic_Solutions_Type
FROM
dbo.General_Ledger_Detail
INNER JOIN dbo.Account_Codes_Sales_OPEX$
ON dbo.General_Ledger_Detail.Accounting_ID =
dbo.Account_Codes_Sales_OPEX$.[Account Code]
INNER JOIN dbo.LogSolOpexCC
ON dbo.General_Ledger_Detail.Cost_Centre = dbo.LogSolOpexCC.Cost_Centre
GROUP BY dbo.General_Ledger_Detail.Accounting_ID,
dbo.General_Ledger_Detail.Cost_Centre,
dbo.General_Ledger_Detail.Product_ID,
dbo.General_Ledger_Detail.Accounted_Amount,
dbo.General_Ledger_Detail.Account_Name,
dbo.General_Ledger_Detail.Accounting_Date,
dbo.Account_Codes_Sales_OPEX$.[Opex Type],
dbo.LogSolOpexCC.Logistic_Solutions_Type
HAVING (dbo.General_Ledger_Detail.Accounting_Date BETWEEN #startdate AND #enddate)
You cannot pass parameters to SQL Server views. https://www.mssqltips.com/sqlservertip/5147/limitations-when-working-with-sql-server-views/
SELECT dbo.General_Ledger_Detail.Accounting_ID, dbo.General_Ledger_Detail.Cost_Centre, dbo.General_Ledger_Detail.Product_ID,
dbo.General_Ledger_Detail.Accounted_Amount AS Amount, dbo.General_Ledger_Detail.Account_Name, dbo.General_Ledger_Detail.Accounting_Date,
dbo.Account_Codes_Sales_OPEX$.[Opex Type], dbo.LogSolOpexCC.Logistic_Solutions_Type
FROM dbo.General_Ledger_Detail INNER JOIN
dbo.Account_Codes_Sales_OPEX$ ON dbo.General_Ledger_Detail.Accounting_ID = dbo.Account_Codes_Sales_OPEX$.[Account Code] INNER JOIN
dbo.LogSolOpexCC ON dbo.General_Ledger_Detail.Cost_Centre = dbo.LogSolOpexCC.Cost_Centre
GROUP BY dbo.General_Ledger_Detail.Accounting_ID, dbo.General_Ledger_Detail.Cost_Centre, dbo.General_Ledger_Detail.Product_ID,
dbo.General_Ledger_Detail.Accounted_Amount, dbo.General_Ledger_Detail.Account_Name, dbo.General_Ledger_Detail.Accounting_Date,
dbo.Account_Codes_Sales_OPEX$.[Opex Type], dbo.LogSolOpexCC.Logistic_Solutions_Type
HAVING (dbo.General_Ledger_Detail.Accounting_Date BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0) AND DATEADD(mm, 1, GETDATE()))

Is there a better way to group date rangers in T-SQL than CASE?

At the moment I'm having to run a lot of SQL queries where the results have to be grouped by date ranges. So far I've been doing it like this:
SELECT COUNT(*)
,CASE
WHEN Don_Date BETWEEN DATEADD(month, - 24, getdate())
AND GETDATE()
THEN 1
WHEN Don_Date BETWEEN DATEADD(month, -48, GETDATE())
AND DATEADD(month, - 24, getdate())
THEN 2
END AS DateRange
FROM #temp
GROUP BY CASE
WHEN Don_Date BETWEEN DATEADD(month, - 24, getdate())
AND GETDATE()
THEN 1
WHEN Don_Date BETWEEN DATEADD(month, -48, GETDATE())
AND DATEADD(month, - 24, getdate())
THEN 2
END
Which works, but it's kind of a pain to write.
I'm having to do this quite a lot, and for a lot of different potential date ranges. Is there a better - as in easier to write/less verbose/more malleable - way of doing this?
You could simplify it with a CTE:
WITH Ranges AS
(
SELECT t.*
,CASE
WHEN Don_Date BETWEEN DATEADD(month, - 24, getdate())
AND GETDATE()
THEN 1
WHEN Don_Date BETWEEN DATEADD(month, -48, GETDATE())
AND DATEADD(month, - 24, getdate())
THEN 2
END AS DateRange
FROM #temp t
)
SELECT Count = COUNT(*), DateRange
FROM Ranges
GROUP BY DateRange
With a join to a virtual values table.
select
rangedesc,COUNT(*)
from
yourtable
left join
(values
(DATEADD(month,-24,getdate()),getdate(), 1),
(DATEADD(month,-48,getdate()),DATEADD(month,-24,getdate()), 2)
) ranges(start,finish,rangedesc)
on yourtable.don_date between ranges.start and ranges.finish
group by rangedesc
If you prefer, you could move the date ranges to a CTE.
Of course, as with all date comparisons, be careful with the borders between two ranges. Compared to your original source code, if a date falls exactly 2 years ago, this method would put it in both ranges, rather than just one.
How about this?
;WITH myDates (DateRange, dtStart, dtEnd)
AS ( SELECT 1, DATEADD(MONTH, -24, GETDATE()), DATEADD(MONTH, 0, GETDATE())
UNION ALL SELECT 2, DATEADD(MONTH, -48, GETDATE()), DATEADD(MONTH, -24, GETDATE())
)
SELECT COUNT(*), DateRange
FROM #temp
JOIN myDates ON don_date BETWEEN dtStart AND dtEnd
GROUP BY DateRange

Resources