Looking for ways to optimize DB2 query - db2

I have a DB2 query as below. I am looking for ways to improve the speed of this one. I have tried visual explain but no indexes were advised by the index advisor. Can somebody have a look at this and advise if something can be done?
There is
CREATE OR REPLACE VIEW PSCMPORDVW
AS
WITH INPROGRESS AS
(
SELECT
DIODR#
, DIDISP
, DIUNIT
, DISTST
, DIAPRV
, DIETAD
, DITRLR AS TRAILER_ID
, DIDR1
, DIETAT
FROM
LOAD
WHERE
DIETAD <> 0
AND DIETAT <> '0000'
ORDER BY
1
)
, STOPGROUP AS
(
SELECT
SOORD STOPORDER
, COUNT(*) STOPSREMAIN
, MIN(SOSTP#) NEXTSTOP
, MAX(SOAPPR) APPTREQ
FROM
STOPOFF
INNER JOIN
INPROGRESS
ON
DIODR# = SOORD
WHERE
SOARDT = 0
GROUP BY
SOORD
ORDER BY
1
)
, STOPAPPTS AS
(
SELECT
SOORD APPTORDER
, SOCUST STOPCUST
, SOEDA ETADATE
, SOETA ETATIME
, SOADT1 EARLYDATE
, SOATM1 EARLYTIME
, SOADT2 LATEDATE
, SOATM2 LATETIME
, SOCTYC NEXTCITY
, SOSTP# APPTSTOP
, SOST NEXTSTATE
FROM
STOPOFF
INNER JOIN
STOPGROUP
ON
STOPORDER = SOORD
AND NEXTSTOP = SOSTP#
)
SELECT
ORDER_NUMBER
, SHIPPER_ID
, SHIPPER_NAME
, SHIPPER_ADDRESS_1
, SHIPPER_ADDRESS_2
, SHIPPER_CITY
, SHIPPER_ST
, SHIPPER_ZIP
, SHIPPER_ZIP_EXT
, LOAD_AT_ID
, LOAD_AT_NAME
, LOAD_AT_ADDRESS_1
, LOAD_AT_ADDRESS_2
, LOAD_AT_CITY
, LOAD_AT_ST
, LOAD_AT_ZIP
, LOAD_AT_ZIP_EXT
, LOAD_AT_LATITUDE
, LOAD_AT_LONGITUDE
, EARLY_PU_DATE_TIME
, LATE_PU_DATE_TIME
, EARLY_DELV_DATE_TIME
, EST_REVENUE
, ORDER_DIV
, CONSIGNEE_ID
, CONSIGNEE_NAME
, CONSIGNEE_ADDRESS_1
, CONSIGNEE_ADDRESS_2
, CONSIGNEE_CITY
, CONSIGNEE_ST
, CONSIGNEE_ZIP
, CONSIGNEE_ZIP_EXT
, CONSIGNEE_LATITUDE
, CONSIGNEE_LONGITUDE
, TRAILER_TYPE
, ORDER_MESSAGE
, ADDITIONAL_STOPS
, CMDTY_CODE
, CMDTY_DESCRIPTION
, ORDER_MILES
, ORDER_WGT
, ORIGIN_CITY_CODE
, ORIGIN_CITY
, ORIGIN_ST
, DEST_CITY_CODE
, DEST_CITY_NAME
, DEST_ST
, PICK_UP_AREA
, PLAN_INFO
, NUMBER_LDS
, NUMBER_DISP
, SHIP_DATE_TIME
, NEW_PICKUP_AREA
, EQUIPMENT_NUMBER
, APPT_REQ
, APPT_MADE
, PRE_T_SEQ
, PRE_T_AREA
, LOAD_DISPATCHED
, CUST_SERV_REP
, NEGOTIATIONS
,
(
CASE
WHEN UNUNIT IS NOT NULL
THEN UNUNIT
ELSE ' '
END
)
UNIT_DISPATCHED
,
(
CASE
WHEN UNSUPR IS NOT NULL
THEN UNSUPR
ELSE ' '
END
)
DRIVER_MGR_CODE
, COALESCE(SUPNAM, ' ') DRIVER_MGR_NAME
,
(
CASE
WHEN UNFMGR IS NOT NULL
THEN UNFMGR
ELSE ' '
END
)
FLEET_MGR_CODE
, COALESCE(FLTNAM, ' ') FLEET_MGR_NAME
,
(
CASE
WHEN UNTRL1 IS NOT NULL
THEN UNTRL1
ELSE ' '
END
)
TRAILER_ID
, DIDISP DISPATCH_NUMBER
, (COALESCE(BCMCNEW, ' ')) FED_MC_ID
, DIUNIT DISPATCHED_UNIT
, CASE
WHEN UNETAD <> 0
AND UNETAT = ''
THEN CVTDATETIM(CHAR(UNETAD),'0000', (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN UNETAD <> 0
THEN CVTDATETIM(CHAR(UNETAD),UNETAT, (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN UNETAD = 0
THEN '0000-00-00T00:00:00-00:00'
END AS ETA_DATE_TIME
, NEXTSTOP
, CASE
WHEN SOARDT <> 0
AND SOARTM = ''
THEN CVTDATETIM(CHAR(SOARDT),'0000', (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN SOARDT <> 0
THEN CVTDATETIM(CHAR(SOARDT),SOARTM, (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN SOARDT = 0
THEN '0000-00-00T00:00:00-00:00'
END AS STOP_ARRIVAL_DATE_TIME
, CASE
WHEN SOLUDT <> 0
AND SOLUTM = ''
THEN CVTDATETIM(CHAR(SOLUDT),'0000', (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN SOLUDT <> 0
THEN CVTDATETIM(CHAR(SOLUDT),SOLUTM, (
SELECT
SUBSTR(DATA_AREA_VALUE, 1109, 2) AS TIMEZONE
FROM
TABLE(QSYS2.DATA_AREA_INFO('COMPAN', '*LIBL'))
)
)
WHEN SOLUDT = 0
THEN '0000-00-00T00:00:00-00:00'
END AS STOP_DEPART_DATE_TIME
, ORBAMT ORDER_INV_AMT
, ORARST AR_STATUS_FLAG
, DISTST SETTLEMENT_FLAG
, DIAPRV APPROVED_FOR_PAY
, BCCARR CARRIER_CODE
, BCNAME CARRIER_NAME
, BCADDR CARRIER_ADDRESS_1
, BCADR2 CARRIER_ADDRESS_2
, BCCITY CARRIER_CITY
, BCST CARRIER_ST
, BCZIP CARRIER_ZIP
FROM
INPROGRESS
INNER JOIN
PSMAINORVW A
ON
DIODR# = ORDER_NUMBER
AND DIDISP = NUMBER_DISP
AND
(
SUBSTR(ORDER_NUMBER, 1, 2) <> 'DH'
AND SUBSTR(ORDER_NUMBER, 1, 1) <> 'M'
)
LEFT OUTER JOIN
STOPOFF
ON
DIODR# = SOORD
AND SOSTP# = 90
LEFT OUTER JOIN
LMCARR
ON
DIUNIT = BCCARR
LEFT OUTER JOIN
MMILES
ON
MMORD# = DIODR#
AND MMRECTYPE = 'D'
AND MMDSP# = DIDISP
EXCEPTION JOIN
ORDBILL B
ON
B.ORODR# = DIODR#
AND B.ORSEQ = ' '
AND ORARST = '1'
LEFT OUTER JOIN
STOPGROUP
ON
STOPORDER = DIODR#
LEFT OUTER JOIN
STOPAPPTS
ON
APPTORDER = STOPORDER
AND APPTSTOP = NEXTSTOP
LEFT OUTER JOIN
UNITS
ON
UNUNIT = DIUNIT
AND UNORD# = ORDER_NUMBER
LEFT OUTER JOIN
SUPMAST
ON
SUPCDE = UNSUPR
LEFT OUTER JOIN
FLTMAST
ON
UNFMGR = FLTCDE
WHERE
DIETAD <> 0
AND DIETAT <> '0000'
RCDFMT PSCMPORDVW ;
I suspect that the below part might be slowing it up. Can someone advise what can be done here?
STOPGROUP AS
(
SELECT
SOORD STOPORDER
, COUNT(*) STOPSREMAIN
, MIN(SOSTP#) NEXTSTOP
, MAX(SOAPPR) APPTREQ
FROM
STOPOFF
INNER JOIN
INPROGRESS
ON
DIODR# = SOORD
WHERE
SOARDT = 0
GROUP BY
SOORD
ORDER BY
1
)

Even though Visual Explain (VE) doesn't advise any indexes ... it can still be used to see how long various parts of your query are taking.
If the
SELECT
SOORD STOPORDER
, COUNT(*) STOPSREMAIN
, MIN(SOSTP#) NEXTSTOP
, MAX(SOAPPR) APPTREQ
Turns out to really be any issue, I'd look at using an Encoded Vector Index (EVI) with aggregate values to speed that up.
I'd suggest breaking it down and building back up while using VE to see where the issues lie.
The only magic wand I might suggest is putting code into a user defined table function (UDTF); assuming you currently plan to use the view like so:
select *
from myview
where something = 'somevalue';
A UDTF would allow for you to explicitly push the selection into the query
select *
from table ( myudtf('somevalue'));

Related

The error message is [Amazon](500310) Invalid operation: This type of correlated subquery pattern is not supported due to internal error

This is the query
CREATE TABLE dw_prestage.check_fact_update
AS
SELECT transaction_id,
transaction_line_id,
subsidiary_id
FROM ( SELECT transaction_id,
transaction_line_id,
subsidiary_id
FROM( SELECT
document_number ,
transaction_number ,
transaction_id ,
transaction_line_id ,
transaction_order ,
custom_form_id ,
document_status ,
transaction_type ,
currency_id ,
trandate ,
exchange_rate ,
account_id ,
amount ,
amount_foreign ,
gross_amount ,
net_amount ,
net_amount_foreign ,
quantity ,
item_id ,
item_unit_price ,
tax_item_id ,
tax_amount ,
location_id ,
class_id ,
subsidiary_id ,
accounting_period_id ,
check_id ,
check_type ,
created_by_id ,
create_date ,
date_last_modified ,
trx_type ,
memo
FROM dw_prestage.check_fact a2
WHERE NOT EXISTS ( SELECT 1 FROM dw_prestage.check_fact_insert b2
WHERE b2.transaction_id = a2.transaction_id
AND b2.transaction_line_id = a2.transaction_line_id
AND a2.subsidiary_id = b2.subsidiary_id
)
MINUS
SELECT
document_number ,
transaction_number ,
transaction_id ,
transaction_line_id ,
transaction_order ,
custom_form_id ,
document_status ,
transaction_type ,
currency_id ,
trandate ,
exchange_rate ,
account_id ,
amount ,
amount_foreign ,
gross_amount ,
net_amount ,
net_amount_foreign ,
quantity ,
item_id ,
item_unit_price ,
tax_item_id ,
tax_amount ,
location_id ,
class_id ,
subsidiary_id ,
accounting_period_id ,
check_id ,
check_type ,
created_by_id ,
create_date ,
date_last_modified ,
trx_type ,
memo
FROM dw_stage.check_fact a1
WHERE EXISTS ( SELECT 1 FROM dw_prestage.check_fact b1
WHERE b1.transaction_id = a1.transaction_id
AND b1.transaction_line_id = a1.transaction_line_id
AND a1.subsidiary_id = b1.subsidiary_id
)
)
) a
WHERE NOT EXISTS (SELECT 1
FROM dw_prestage.check_fact_insert aa
WHERE aa.transaction_id = a.transaction_id
AND aa.transaction_line_id = a.transaction_line_id);
plz suggest any alternative way to replace this query.
The error is because the queries in your NOT EXISTS clauses reference a table outside of the of the clause. Convert the NOT EXISTS clause into a LEFT JOIN with a predicate to exclude any matches. This pattern is often called an "anti-join".
Current:
FROM (…) a
WHERE NOT EXISTS (SELECT 1
FROM dw_prestage.check_fact_insert aa
WHERE aa.transaction_id = a.transaction_id
AND aa.transaction_line_id = a.transaction_line_id)
Rewrite:
FROM (…) a
LEFT JOIN dw_prestage.check_fact_insert aa
ON a.transaction_id = aa.transaction_id
AND a.transaction_line_id = aa.transaction_line_id
WHERE aa.transaction_id IS NULL

SUM OVER PARTITION to calculate running total

I am trying to modify my query to include a running total for each county in my report. Below is my working query with an attempt to use SUM OVER PARTITION commented out:
SELECT DATEPART(MONTH, r.received_date) AS [MonthID] ,
DATENAME(MONTH, r.received_date) AS [Month] ,
o.name AS [CountyName] ,
rsc.description AS [Filing] ,
COUNT(r.id) AS [Request_Total] ,
CAST (AVG(CAST (DATEDIFF(HOUR, received_date, completion_date) AS DECIMAL(8,2))) / 24 AS DECIMAL(8,2)) AS [Total_Time_Days]
--SUM(r.id) OVER (PARTITION BY o.name) AS [TotalFilings]
FROM dbo.requests AS [r]
INNER JOIN dbo.organizations AS [o] ON o.id = r.submitted_to_organiztion_id
INNER JOIN dbo.request_status_codes AS [rsc] ON rsc.code = r.request_status_code
WHERE r.submitted_to_organiztion_id < 68
AND r.request_type_code = 1
AND CAST(r.received_date AS DATE) >= '01/01/2016'
AND CAST(r.received_date AS DATE) <= '06/30/2016'
AND o.name = 'Alachua'
GROUP BY DATENAME(MONTH, r.received_date) ,
DATEPART(MONTH, r.received_date) ,
o.name ,
rsc.description
ORDER BY DATEPART(MONTH, r.received_date) ,
CountyName ,
Filing;
And the results look correct:
Perhaps I am misusing the SUM PARTITION BYbut my end goal is to add an additional column that will sum the filing types for each county by month.
For example, the additional column for the month of January should be 13,654 while February should be 14,238 and so on.
Could I get some advice on how to get this query working correctly? Thanks,
Not sure this is the best way or more efficient, but I was able to create a sub-query to obtain the results I wanted. I do believe a CTE or use of a Windows function would be better, but I haven't been able to get it to work. Here is my query however:
SELECT X.[MonthID] ,
X.[Month] ,
X.[CountyName] ,
X.[Filing] ,
X.[Avg_Time_Days] ,
SUM(X.Request_Total) AS [Total_Requests]
FROM ( SELECT DATEPART(MONTH, r.received_date) AS [MonthID] ,
DATENAME(MONTH, r.received_date) AS [Month] ,
o.name AS [CountyName] ,
rsc.description AS [Filing] ,
COUNT(r.id) AS [Request_Total] ,
CAST (AVG(CAST (DATEDIFF(HOUR, received_date,
completion_date) AS DECIMAL(8, 2)))
/ 24 AS DECIMAL(8, 2)) AS [Avg_Time_Days]
--, SUM(r.id) OVER (PARTITION BY o.name, rsc.description) AS [TotalFilings]
FROM dbo.requests AS [r]
INNER JOIN dbo.organizations AS [o] ON o.id = r.submitted_to_organiztion_id
INNER JOIN dbo.request_status_codes AS [rsc] ON rsc.code = r.request_status_code
WHERE r.submitted_to_organiztion_id < 68
AND r.request_type_code = 1
AND CAST(r.received_date AS DATE) >= '01/01/2016'
AND CAST(r.received_date AS DATE) <= '06/30/2016'
--AND o.name = 'Alachua'
GROUP BY DATENAME(MONTH, r.received_date) ,
DATEPART(MONTH, r.received_date) ,
o.name ,
rsc.description
--, r.id
--ORDER BY DATEPART(MONTH, r.received_date) ,
-- CountyName ,
-- Filing
) AS X
GROUP BY X.[MonthID] ,
X.[Month] ,
X.[CountyName] ,
X.[Filing] ,
X.[Avg_Time_Days]
ORDER BY X.[MonthID] ,
X.[Month] ,
X.[CountyName] ,
X.[Filing];

T_SQL The multi part identifier could not be bound error

I have a query which works fine, but I am trying to create a dynamic pivot out of it to get a better end result table.
I found this on SO but I cant relate it to my issue.
The multi-part identifier could not be bound
My working code is this:
DECLARE #RangeDate as date
set #RangeDate = (select distinct cd.weDate from CM_DATA cd where cd.year = 2015 and cd.week = 45)
set #RangeDate = DATEADD(WW, -7, #RangeDate)
DECLARE #SQL as VARCHAR(MAX)
DECLARE #Columns AS VARCHAR(MAX)
SELECT #Columns =
COALESCE(#Columns + ', ','') + QUOTENAME(YearWeek)
FROM
(
SELECT DISTINCT YearWeek
FROM CM_DATA
where weDate >= #RangeDate
) AS B
SET #SQL = '
WITH PivotData AS
(
select cd.Country
, cd.Chain
, cd.YearWeek
, left(sm.Planogram, 2) as planogram
, cd.StoreNo
, cd.UID
, cd.ShortCode
, lp.Family
, lp.ColourShort
, pr.type
, cd.Volume
, ul.WOSOR
from vw_V2_UsrVarLst ul
left join CM_DATA cd on cd.Country = ul.CountryCode and cd.Chain = ul.Chain
left join V2_StoreMaster sm on sm.CountryCode = ul.CountryCode and sm.Chain = ul.Chain and sm.StoreNo = cd.StoreNo and sm.StoreNm = cd.StoreNm and cd.YearWeek between sm.YYYYWW and sm.YYYYWWEND
left join tblProducts pr ON pr.[COUNTRY CODE] = ul.CountryCode and pr.SKU = cd.UID
left join V2_LanguagePack LP ON LP.ShortCode = cd.ShortCode AND lp.Lang = ul.UsrLang
where cd.Country = ul.CountryCode and cd.Chain = ul.Chain and planogram is not null and left(cd.UID, 10) in (select lv.UID from V2_live lv where lv.CountryCode = ul.CountryCode and lv.Chain = ul.Chain and cd.YearWeek between lv.YYYYWW and lv.YYYYWWEND) and cd.weDate >= ' + #RangeDate + ' and sm.Planogram != ''Z''
)
select cd.Country
, cd.Chain
, left(sm.Planogram, 2) as planogram
, cd.StoreNo
, cd.UID
, cd.ShortCode
, lp.Family
, lp.ColourShort
, pr.type
, cd.Volume
, ' + #Columns + '
, ul.WOSOR
FROM PivotData
PIVOT
(
SUM(Volume)
FOR YearWeek
IN(' + #Columns + ')
) AS PivotResult'
EXEC (#SQL)
Can anyone spot what up here
KR
Martin
Try SELECT #SQL instead of your EXEC.
You probably must set the output to Text and use the query options (right click into the query window) to set the max length of text output to a higher value (maximum is 8192).
Than you can paste the result of your dynamic SQL into a new query window and execute this there. You should get a speaking error message and you should even jump to the right place with a double click...
Good luck!

How to get the rows position numbers of a table result

This is my code
Select #pos = Pos, #ptsReputacion = isnull(AA.PtsReputacion,0)
From
(Select
ROW_NUMBER() OVER (ORDER BY #ptsReputacion DESC) AS Pos
, USUARIO.CodUsuario
, PtsReputacion = (Select isnull(sum(Puntos),0) as Puntos
From USUARIO_RANKING_INTERES
Where USUARIO_RANKING_INTERES.CodUsuario = #codUsuario)
, USUARIO.CantIntentos as Intentos
, USUARIO.CantAciertos as Aciertos
, USUARIO.CantFallos as Fallos
, isnull(USUARIO.PG,0) as PG
, isnull(USUARIO.PE,0) as PE
, isnull(USUARIO.PP,0) as PP
, isnull(USUARIO.TiempoTotal,0) as TiempoTotal
From USUARIO) AA
Where AA.CodUsuario = #codUsuario
But it doesn't works because the Pos field has an other value. For example, it gives 2 instead 1.
I want to know how to get the row position number one by one ordered by a variable (because the field is a subquery).
It looks like you really want to do something like the below. I'm using CTEs because that makes it easier to read.
WITH BaseQuery AS
(
SELECT
U.CodUsuario
, PtsReputacion = (Select isnull(sum(Puntos),0) as Puntos
From USUARIO_RANKING_INTERES
Where USUARIO_RANKING_INTERES.CodUsuario = U.CodUsuario)
, USUARIO.CantIntentos as Intentos
, USUARIO.CantAciertos as Aciertos
, USUARIO.CantFallos as Fallos
, isnull(USUARIO.PG,0) as PG
, isnull(USUARIO.PE,0) as PE
, isnull(USUARIO.PP,0) as PP
, isnull(USUARIO.TiempoTotal,0) as TiempoTotal
FROM USUARIO U
),
RNQuery AS
(
SELECT
*
, ROW_NUMBER() OVER (ORDER BY PtsReputacion DESC) AS Pos
FROM
BaseQuery
)
SELECT
#pos = Pos
, #ptsReputacion = isnull(AA.PtsReputacion,0)
FROM
RNQuery AS AA
WHERE
AA.CodUsuario = #codUsuario

Extract data from Windows Server Update Services (WSUS) using SQL query

I have never used WSUS, so I really dont know how to get right data. The goal is to have a table with three columns: Computer Group, Computer Name, # of needed updates
I found out here: Microsoft Developer Network
that WSUS uses SQL server to store data that I need and I can connect to it via \.\pipe\MSSQL$MICROSOFT##SSEE\sql\query. I prefer this method, not PowerShell or something else, because finally I need this data in other sqlserver.
Could somebody please help me with SQL query that will extract needed info? I cant see anything familiar in database or PUBLIC_VIEWs. Many thanks.
Using SUSDB here is a minimal version with columns you requested:
Select tg.Name as ComputerGroup, ct.FullDomainName as ComputerName, Count(*) As Needed
From tbComputerTarget AS ct
Join tbComputerTargetDetail ctd on ctd.TargetId = ct.TargetId
Join tbTargetInTargetGroup tgct on tgct.TargetId = ct.TargetId
Join tbTargetGroup tg on tg.TargetGroupId = tgct.TargetGroupId
Join tbUpdateStatusPerComputer as s on ct.TargetID = s.TargetID And SummarizationState In(2,3,6)
Group By tg.Name, ct.FullDomainName;
Using SUSDB, here is a summary by computer with more columns that you requested:
With cteUpdateInstallationInfo As(
SELECT u.UpdateID
, ct.ComputerID
, (CASE WHEN usc.SummarizationState IS NULL OR usc.SummarizationState = 1 THEN (CASE WHEN ISNULL(u.LastUndeclinedTime, u.ImportedTime) < ct.EffectiveLastDetectionTime THEN 1 ELSE 0 END) ELSE usc.SummarizationState END) AS State
FROM dbo.tbUpdate AS u
JOIN dbo.tbRevision AS r ON u.LocalUpdateID = r.LocalUpdateID And r.IsLatestRevision = 1
JOIN dbo.tbProperty AS p ON r.RevisionID = p.RevisionID And p.ExplicitlyDeployable = 1
CROSS JOIN dbo.tbComputerTarget AS ct
LEFT JOIN dbo.tbUpdateStatusPerComputer AS usc ON u.LocalUpdateID = usc.LocalUpdateID AND ct.TargetID = usc.TargetID
WHERE u.IsHidden = 0
), Summary as(
Select ComputerId
, Count(*) as Total
, Sum(case When State = 0 Then 1 else 0 end) as NoStatus
, Sum(case When State = 1 Then 1 else 0 end) as NotApp
, Sum(case When State In(2,3,6) Then 1 else 0 end) as Needed
, Sum(case When State = 4 Then 1 else 0 end) as Installed
, Sum(case When State = 5 Then 1 else 0 end) as Failed
From cteUpdateInstallationInfo
Group by ComputerId
), TimeZone as (
Select DATEDIFF(mi, GetUtcDate(), GetDate()) as TimeZoneMinutes
)
Select ct.ComputerId
, ct.FullDomainName
, ct.IPAddress
, tg.Name as TargetGroupName
, Total, NoStatus, NotApp, Needed, Failed, Installed
, Dateadd(mi, TimeZoneMinutes, ct.EffectiveLastDetectionTime) As LastDetectLocalTime
, Dateadd(mi, TimeZoneMinutes, ct.LastReportedStatusTime) as LastReportLocalTime
, Dateadd(mi, TimeZoneMinutes, ct.LastSyncTime) As LastContactLocalTime
, LastSyncResult
, Dateadd(mi, TimeZoneMinutes, ct.LastReportedRebootTime) As LastRebootLocalTime
, Dateadd(mi, TimeZoneMinutes, ct.LastInventoryTime) As LastInventoryLocalTime
, Dateadd(mi, TimeZoneMinutes, ct.LastNameChangeTime) As LastNameChangeLocalTime
--, IsRegistered
--, OSMajorVersion, OSMinorVersion, OSBuildNumber, OSServicePackMajorNumber,OSServicePackMinorNumber
, OSLocale
, ComputerMake
, ComputerModel
, BiosVersion
, BiosName
, BiosReleaseDate
, ProcessorArchitecture
--, LastStatusRollupTime LastReceivedStatusRollupNumber LastSentStatusRollupNumber
--, SamplingValue, CreatedTime, SuiteMask, OldProductType, NewProductType, SystemMetrics
, ClientVersion
--, TargetGroupMembershipChanged
, OSFamily
, OSDescription
, OEM
, DeviceType
, FirmwareVersion
, MobileOperator
From Summary as s
Join TimeZone as tz on 1=1
JOIN dbo.tbComputerTarget AS ct on ct.ComputerID = s.ComputerId
Join tbComputerTargetDetail ctd on ctd.TargetId = ct.TargetId
Join tbTargetInTargetGroup tgct on tgct.TargetId = ct.TargetId
Join tbTargetGroup tg on tg.TargetGroupId = tgct.TargetGroupId
Also as a bonus here is a summary by update:
With Summary as(
Select UpdateId
, Count(*) as Total
, Sum(case When State = 0 Then 1 else 0 end) as NoStatus
, Sum(case When State = 1 Then 1 else 0 end) as NotApp
, Sum(case When State In(2,3,6) Then 1 else 0 end) as Needed
, Sum(case When State = 4 Then 1 else 0 end) as Installed
, Sum(case When State = 5 Then 1 else 0 end) as Failed
From PUBLIC_VIEWS.vUpdateInstallationInfo
Group BY UpdateId
), TimeZone as (
Select DATEDIFF(mi, GetUtcDate(), GetDate()) as TimeZoneMinutes
)
Select s.UpdateId
, u.IsDeclined
, u.PublicationState
, u.DefaultTitle as Title
, u.KnowledgebaseArticle as KBArticle
, Total, NoStatus, NotApp, Needed, Failed, Installed
, Dateadd(mi, TimeZoneMinutes, u.CreationDate) As ReleaseLocalTime
, Dateadd(mi, TimeZoneMinutes, u.ArrivalDate) As ArrivalLocalTime
From summary as s
Join TimeZone as tz on 1=1
Join PUBLIC_VIEWS.vUpdate as u on u.UpdateID = s.UpdateId