Determining the count of columns with a value greater than 0 - tsql

Ok guys/gals...
Here's my result set:
and here's the ultimate results set I want
to achieve the result, I am currently using n (3) subqueries... which is not ideal...
declare #userId int = 436
select
(select count(PRODUCT_ID) from sl_suggested_asset where PRODUCT_ID > 0 and user_id = #userId) As 'PRODUCT_ID',
(select count(DIGI_DOC_ID) from sl_suggested_asset where DIGI_DOC_ID > 0 and user_id = #userId) As 'DIGI_DOC_ID',
(select count(QR_CODE_ID) from sl_suggested_asset where qr_code_id > 0 and user_id = #userId) As 'QR_CODE_ID'
what I would like is to use either a cte or an aggregate...
here's what I was thinking...
select count(product_id), count(DIGI_DOC_ID), count(qr_code_id), user_id
from sl_suggested_asset
where user_id = 436
group by user_id
but this gives me the total number of rows...
so my having clause should be used but that means that I need to have the proper group by predicate... this is where I'm stuck...
here are some examples of what I've tried...
select
count(PRODUCT_ID) As 'PRODUCT_ID'
, count(DIGI_DOC_ID) As 'DIGI_DOC_ID'
, count(QR_CODE_ID) As 'QR_CODE_ID'
, user_id
from sl_suggested_asset
where
PRODUCT_ID > 0
or
DIGI_DOC_ID > 0
or
QR_CODE_ID > 0
and
user_id = 436
group by user_id
and I get...
... here I change the order of the where clause conditions...
select
count(PRODUCT_ID) As 'PRODUCT_ID'
, count(DIGI_DOC_ID) As 'DIGI_DOC_ID'
, count(QR_CODE_ID) As 'QR_CODE_ID'
, user_id
from sl_suggested_asset
where
user_id = 436
and
PRODUCT_ID > 0
or
DIGI_DOC_ID > 0
or
QR_CODE_ID > 0
group by user_id
... and I get the same result as above ...
... now I change the where clause to = 0 and get the same result, which means the where clause is being completely ignored...
select
count(PRODUCT_ID) As 'PRODUCT_ID'
, count(DIGI_DOC_ID) As 'DIGI_DOC_ID'
, count(QR_CODE_ID) As 'QR_CODE_ID'
, user_id
from sl_suggested_asset
where
user_id = 436
and
PRODUCT_ID = 0
or
DIGI_DOC_ID = 0
or
QR_CODE_ID = 0
group by user_id
... lastly, if I change the ors to ands I get zero results ...
select
count(PRODUCT_ID) As 'PRODUCT_ID'
, count(DIGI_DOC_ID) As 'DIGI_DOC_ID'
, count(QR_CODE_ID) As 'QR_CODE_ID'
, user_id
from sl_suggested_asset
where
user_id = 436
and
PRODUCT_ID = 0
and
DIGI_DOC_ID = 0
and
QR_CODE_ID = 0
group by user_id

Just use some CASE STATEMENTS on the Query
SELECT SUM(
CASE
WHEN PRODUCT_ID > 0
THEN 1
ELSE 0
END
) as PRODUCT_ID ,
SUM(
CASE
WHEN DIGI_DOC_ID>0
THEN 1
ELSE 0
END
) as DIGI_DOC_ID,
SUM(
CASE
WHEN QR_CODE_ID>0
THEN 1
ELSE 0
END
) as QR_CODE_ID
FROM sl_SUGGESTED_ASSET
WHERE USER_ID =436
Have a great day!

Related

Aggregating columns and getting count of values as row

I have a query output as below:
ID ID2 Working Leave Off Day
14595 76885302 10 0 0
178489 78756208 0 0 1
178489 78756208 0 1 0
I want to receive an output like below:
ID ID2 code value
14595 76885302 Working 10
178489 78756208 Off day 1
178489 78756208 Leave 1
My query is like below:
select tei.organisationunitid,pi.trackedentityinstanceid as tei,
count(case when tedv.value = 'Working' then tedv.value end) Working,
count(case when tedv.value = 'Off day' then tedv.value end) Offday,
count(case when tedv.value = 'Leave' then tedv.value end) Leave
from programstageinstance psi
inner join programinstance pi on pi.programinstanceid = psi.programinstanceid
inner join trackedentitydatavalue tedv on tedv.programstageinstanceid = psi.programstageinstanceid
inner join dataelement de on de.dataelementid = tedv.dataelementid
inner join trackedentityinstance tei on tei.trackedentityinstanceid = pi.trackedentityinstanceid
where psi.executiondate between '2017-01-01' and '2019-06-01'
and de.uid in ('x2222EGfY4K')
and psi.programstageid in (select programstageid
from programstage
where uid = 'CLoZpO22228')
and tei.organisationunitid in (select organisationunitid
from organisationunit
where path like '%Spd2222fvPr%')
group by pi.trackedentityinstanceid,de.uid,tei.organisationunitid,tedv.value
How can I achieve this?
I would try the JSON approach. I made a step-by-step fiddle:
demo:db<>fiddle
SELECT
id, id2,
elements ->> 'code' AS code,
SUM((elements ->> 'value')::int) AS value
FROM (
SELECT
id,
id2,
json_build_object('code', 'working', 'value', working) AS working,
json_build_object('code', 'leave', 'value', leave) AS leave,
json_build_object('code', 'off_day', 'value', off_day) AS off_day
FROM
mytable
) s,
unnest(ARRAY[working, leave, off_day]) as elements
GROUP BY 1,2,3
HAVING SUM((elements ->> 'value')::int) > 0

Capture First Character of Last Group of 1s in a Binary Series Part II: Multiple IDs

I have data something like this:
ID 1 1 1 1 1 1 1 1 1 1 1 1
Month J F M A M J J A S O N D
Status 1 0 0 1 0 1 0 0 1 1 1 1
ID 2 2 2 2 2 2 2 2 2 2 2 2
Month J F M A M J J A S O N D
Status 1 0 1 0 1 0 1 0 1 0 1 1
ID 3 3 3 3 3 3 3 3 3 3 3 3
Month J F M A M J J A S O N D
Status 0 0 0 0 0 0 0 0 0 0 0 1
Using t-SQL, I am trying to capture the month corresponding to the first STATUS = 1 in the last group of 1s for each ID, i.e., September, November and December in this example.
Here is the code I'm using:
IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL DROP TABLE #Temp1
;WITH PARTITIONED1 AS
(SELECT t0.ID
, t0.Year_Month
, LAST_VALUE(t0.Year_Month) OVER (PARTITION BY t0.Account_Number ORDER BY t0.Year_Month) AS STATUS
, ROW_NUMBER() OVER (PARTITION BY t0.Account_Number ORDER BY t0.Year_Month) AS rn1
FROM #Temp0 t0
)
SELECT *
INTO #Temp1
FROM PARTITIONED1 p1
ORDER BY t0.ID
, t0.Year_Month
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL DROP TABLE #Temp
SELECT *
INTO #Temp
FROM #Temp1 t1
WHERE t1.rn1 = (SELECT MAX(b.rn1) + 1 FROM #Temp1 b WHERE b.STATUS = 0)
GROUP BY t1.ID
, t1.Year_Month
, t1.rn1
However, this just returns the last instance where STATUS = 1 is achieved overall as the first 1 of the last group of 1s, in this case January.
I've tried using CASE statements and grouping in various combinations (hence the intermediate step reading the data into #Temp1), but have not been able to get results for all three IDs; is anyone able to assist?
Thanks in advance!
Assuming Ju for June and Jl for July:
--Sample Data
IF OBJECT_ID('tempdb..#Temp0') IS NOT NULL DROP TABLE #Temp0
CREATE TABLE #Temp0 (ID INT, Year_Month VARCHAR(1), Status INT)
INSERT INTO #Temp0
VALUES(1,'J',1),(1,'F',0),(1,'M',0),(1,'A',1),(1,'M',0),(1,'J',1),(1,'J',0),(1,'A',0),(1,'S',1),(1,'O',1),(1,'N',1),(1,'D',1),(2,'J',1),(2,'F',0),(2,'M',1),(2,'A',0),(2,'M',1),(2,'J',0),(2,'J',1),(2,'A',0),(2,'S',1),(2,'O',0),(2,'N',1),(2,'D',1),(3,'J',0),(3,'F',0),(3,'M',0),(3,'A',0),(3,'M',0),(3,'J',0),(3,'J',0),(3,'A',0),(3,'S',0),(3,'O',0),(3,'N',0),(3,'D',1);
--Query
WITH A
AS ( SELECT *,
CASE Year_Month
WHEN 'J' THEN 1
WHEN 'F' THEN 2
WHEN 'M' THEN 3
WHEN 'A' THEN 4
WHEN 'M' THEN 5
WHEN 'Ju' THEN 6
WHEN 'Jl' THEN 7
WHEN 'A' THEN 8
WHEN 'S' THEN 9
WHEN 'O' THEN 10
WHEN 'N' THEN 11
WHEN 'D' THEN 12
END
AS MonthNumber
FROM #Temp0 ),
StartingPoints
AS ( SELECT ID,
Year_Month,
MonthNumber,
Status
FROM A
WHERE NOT EXISTS
(
SELECT 1
FROM A
AS B
WHERE B.ID=A.ID
AND B.Status=A.Status-1
) ),
MonthRanking
AS ( SELECT A.*,
ROW_NUMBER( ) OVER( PARTITION BY A.ID ORDER BY A.MonthNumber )
AS rownum
FROM A
INNER JOIN
(
SELECT ID,
MAX( MonthNumber )+1
AS StartOfLastGroup
FROM StartingPoints
GROUP BY ID
)
AS B
ON A.ID=B.ID
AND A.MonthNumber>=B.StartOfLastGroup )
SELECT *
FROM MonthRanking
WHERE rownum=1;
Results:
If Month Names are recorded in Full as in July, June then this would work as well:
WITH StartingPoints
AS (SELECT ID,
Year_Month,
MonthNUmber = MONTH('01-'+Year_Month+'-2010'),
Status
FROM #Temp0
WHERE NOT EXISTS
(
SELECT 1
FROM #Temp0 AS B
WHERE B.ID = #Temp0.ID
AND B.Status = #Temp0.Status - 1
)),
MonthRanking
AS (SELECT A.*,
ROW_NUMBER() OVER(PARTITION BY A.ID ORDER BY MONTH('01-'+A.Year_Month+'-2010')) AS rownum
FROM #Temp0 AS A
INNER JOIN
(
SELECT ID,
MAX(MonthNumber) + 1 AS StartOfLastGroup
FROM StartingPoints
GROUP BY ID
) AS B ON A.ID = B.ID
AND MONTH('01-'+A.Year_Month+'-2010') >= B.StartOfLastGroup)
SELECT *
FROM MonthRanking
WHERE rownum = 1;
Results:
And if we assume that the data is as Iamdave assumes then it simply like so:
WITH StartingPoints
AS (SELECT ID,
Year_Month,
Status
FROM #Temp0
WHERE NOT EXISTS
(
SELECT 1
FROM #Temp0 AS B
WHERE B.ID = #Temp0.ID
AND B.Status = #Temp0.Status - 1
)),
MonthRanking
AS (SELECT A.*,
ROW_NUMBER() OVER(PARTITION BY A.ID ORDER BY Year_Month) AS rownum
FROM #Temp0 AS A
INNER JOIN
(
SELECT ID,
MAX(Year_Month) + 1 AS StartOfLastGroup
FROM StartingPoints
GROUP BY ID
) AS B ON A.ID = B.ID
AND A.Year_Month >= B.StartOfLastGroup)
SELECT *
FROM MonthRanking
WHERE rownum = 1;
Results:
You can do this with a couple derived tables that stack two window functions on top of one another (which can't be done in the same select). I have assumed that your data is slightly different to the table you have provided, based on the column names in your query. If they are not as I have them below, I strongly recommend having a look at how you store your data:
declare #t table(ID int, YearMonth int,StatusValue bit);
insert into #t values (1,201501,1),(1,201502,0),(1,201503,0),(1,201504,1),(1,201505,0),(1,201506,1),(1,201507,0),(1,201508,0),(1,201509,1),(1,201510,1),(1,201511,1),(1,201512,1),(2,201601,1),(2,201602,0),(2,201603,1),(2,201604,0),(2,201605,1),(2,201606,0),(2,201607,1),(2,201608,0),(2,201609,1),(2,201610,0),(2,201611,1),(2,201612,1),(3,201701,0),(3,201702,0),(3,201703,0),(3,201704,0),(3,201705,0),(3,201706,0),(3,201707,0),(3,201708,0),(3,201709,0),(3,201710,0),(3,201711,0),(3,201712,1);
with c as
(
select ID
,YearMonth
,StatusValue
,case when StatusValue = 1
and lead(StatusValue,1,1) over (partition by ID
order by YearMonth desc) = 0
then 1
else 0
end as c
from #t
), sc as
(
select ID
,YearMonth
,StatusValue
,sum(c) over (partition by ID order by YearMonth desc) as sc
from c
where c = 1
)
select ID
,YearMonth
,StatusValue
from sc
where sc = 1
order by ID;
Output:
+----+-----------+-------------+
| ID | YearMonth | StatusValue |
+----+-----------+-------------+
| 1 | 201509 | 1 |
| 2 | 201611 | 1 |
| 3 | 201712 | 1 |
+----+-----------+-------------+

how to select top 10 without duplicates

Using SQL Server 2012
I need to select TOP 10 Producer based on a ProducerCode. But the data is messed up, users were entering same Producers just spelled differently and with the same ProducerCode.
So I just need TOP 10, so if the ProducerCode is repeating, I just want to pick the first one in a list.
How can I achieve that?
Sample of my data
;WITH cte_TopWP --T
AS
(
SELECT distinct ProducerCode, Producer,SUM(premium) as NetWrittenPremium,
SUM(CASE WHEN PolicyType = 'New Business' THEN Premium ELSE 0 END) as NewBusiness1,
SUM(CASE WHEN PolicyType = 'Renewal' THEN Premium ELSE 0 END) as Renewal1,
SUM(CASE WHEN PolicyType = 'Rewrite' THEN Premium ELSE 0 END) as Rewrite1
FROM ProductionReportMetrics
WHERE YEAR(EffectiveDate) = 2016 AND TransactionType = 'Policy' AND CompanyLine = 'Arch Insurance Company'--AND ProducerType = 'Wholesaler'
GROUP BY ProducerCode,Producer
)
,
cte_Counts --C
AS
(
SELECT distinct ProducerCode, ProducerName, COUNT (distinct ControlNo) as Submissions2,
SUM(CASE WHEN QuotedPremium IS NOT NULL THEN 1 ELSE 0 END) as Quoted2,
SUM(CASE WHEN Type = 'New Business' AND Status IN ('Bound','Cancelled','Notice of Cancellation') THEN 1 ELSE 0 END ) as NewBusiness2,
SUM(CASE WHEN Type = 'Renewal' AND Status IN ('Bound','Cancelled','Notice of Cancellation') THEN 1 ELSE 0 END ) as Renewal2,
SUM(CASE WHEN Type = 'Rewrite' AND Status IN ('Bound','Cancelled','Notice of Cancellation') THEN 1 ELSE 0 END ) as Rewrite2,
SUM(CASE WHEN Status = 'Declined' THEN 1 ELSE 0 END ) as Declined2
FROM ClearanceReportMetrics
WHERE YEAR(EffectiveDate)=2016 AND CompanyLine = 'Arch Insurance Company'
GROUP BY ProducerCode,ProducerName
)
SELECT top 10 RANK() OVER (ORDER BY NetWrittenPremium desc) as Rank,
t.ProducerCode,
c.ProducerName as 'Producer',
NetWrittenPremium,
t.NewBusiness1,
t.Renewal1,
t.Rewrite1,
c.[NewBusiness2]+c.[Renewal2]+c.[Rewrite2] as PolicyCount,
c.Submissions2,
c.Quoted2,
c.[NewBusiness2],
c.Renewal2,
c.Rewrite2,
c.Declined2
FROM cte_TopWP t --LEFT OUTER JOIN tblProducers p on t.ProducerCode=p.ProducerCode
LEFT OUTER JOIN cte_Counts c ON t.ProducerCode=c.ProducerCode
You should use ROW_NUMBER to fix your issue.
https://msdn.microsoft.com/en-us/library/ms186734.aspx
A good example of this is the following answer:
https://dba.stackexchange.com/a/22198
Here's the code example from the answer.
SELECT * FROM
(
SELECT acss_lookup.ID AS acss_lookupID,
ROW_NUMBER() OVER
(PARTITION BY your_distinct_column ORDER BY any_column_you_think_is_appropriate)
as num,
acss_lookup.product_lookupID AS acssproduct_lookupID,
acss_lookup.region_lookupID AS acssregion_lookupID,
acss_lookup.document_lookupID AS acssdocument_lookupID,
product.ID AS product_ID,
product.parent_productID AS productparent_product_ID,
product.label AS product_label,
product.displayheading AS product_displayheading,
product.displayorder AS product_displayorder,
product.display AS product_display,
product.ignorenewupdate AS product_ignorenewupdate,
product.directlink AS product_directlink,
product.directlinkURL AS product_directlinkURL,
product.shortdescription AS product_shortdescription,
product.logo AS product_logo,
product.thumbnail AS product_thumbnail,
product.content AS product_content,
product.pdf AS product_pdf,
product.language_lookupID AS product_language_lookupID,
document.ID AS document_ID,
document.shortdescription AS document_shortdescription,
document.language_lookupID AS document_language_lookupID,
document.document_note AS document_document_note,
document.displayheading AS document_displayheading
FROM acss_lookup
INNER JOIN product ON (acss_lookup.product_lookupID = product.ID)
INNER JOIN document ON (acss_lookup.document_lookupID = document.ID)
)a
WHERE a.num = 1
ORDER BY product_displayheading ASC;
You could do this:
SELECT ProducerCode, MIN(Producer) AS Producer, ...
GROUP BY ProducerCode

Count Distinct with Answer side by side instead of underneath

Here is my query:
SELECT substring(date,1,10), count(distinct id),
CASE WHEN name IS NOT NULL THEN 1 ELSE 0 END
FROM table
WHERE (date >= '2015-09-01')
GROUP BY substring(date,1,10), CASE WHEN name IS NOT NULL THEN 1 ELSE 0 END
ORDER BY substring(date,1,10)
This is my result:
substring count case
2015-09-01 20472 0
2015-09-01 7 1
2015-09-02 20465 0
2015-09-02 470 1
What I want it to look like is this:
substring count count
2015-09-01 20472 7
2015-09-02 20465 470
Thank you!
With PostgreSQL 9.4 or newer, we can filter directly an aggregate with the new FILTER clause:
SELECT substring(date,1,10),
count(distinct id),
count(*) FILTER (WHERE name IS NOT NULL)
FROM table
WHERE (date >= '2015-09-01')
GROUP BY 1
ORDER BY 1
SELECT substring(date,1,10)
, count(distinct CASE WHEN name IS NOT NULL THEN id ELSE null END ) AS count1
, count(distinct CASE WHEN name IS NOT NULL THEN null ELSE id END ) AS count2
FROM event
WHERE (date >= '2015-09-01')
GROUP BY substring(date,1,10)
ORDER BY substring(date,1,10)
This gave me an answer like this: (which is exactly what I wanted so thank you so much)
substring count1 count2
2015-09-01 7 20472
2015-09-02 470 20465
Use case in count to get columns for some condition (name IS NOT NULL), like this:
SELECT substring(date,1,10)
, count(distinct CASE WHEN name IS NOT NULL THEN id ELSE null END ) AS count1
, count(distinct CASE WHEN name IS NOT NULL THEN null ELSE id END ) AS count2
FROM table
WHERE (date >= '2015-09-01')
GROUP BY substring(date,1,10)
ORDER BY substring(date,1,10)
you can also use subquery to create columns:
SELECT dt, Count(id1) count1, Count(distinct id2) count2
FROM (
SELECT distinct substring(date,1,10) AS dt
, CASE WHEN name IS NOT NULL THEN id ELSE null END AS id1
, CASE WHEN name IS NOT NULL THEN null ELSE id END AS id2,
FROM table
WHERE (date >= '2015-09-01')) d
GROUP BY dt
ORDER BY dt

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