Related
Here is my code:
arrival_cluster_raw as (
SELECT
routes.uc_id ,
cg.cluster_id ,
cg.cluster_centroid ,
routes.imei ,
routes.time_created::date as campaign_date,
min(routes.time_created) as m_per_imei_cluster
FROM cluster_groups as cg
group by 1,2,3,4,5
)
,
arrival_cluster_final as
(
select uc_id, campaign_date, cluster_id, cluster_centroid , date_trunc('second', AVG(m_per_imei_cluster::TIME)) as avg_arrival_time,
count(case when m_per_imei_cluster::TIME < (select AVG(m_per_imei_cluster::TIME) from arrival_cluster_raw) then 1 else null END) as "num_of_arrival_teams_before_avg_time"
,count(case when m_per_imei_cluster::TIME > (select AVG(m_per_imei_cluster::TIME) from arrival_cluster_raw) then 1 else null END) as "num_of_arrival_teams_after_avg_time"
FROM arrival_cluster_raw
group by uc_id,cluster_id, cluster_centroid ,campaign_date
)
The problem is that in the "arrival_cluster_final", the average value of the entire cluster
is being compared whereas I want to compare the average value for the combination of uc_id,cluster_id, cluster_centroid ,campaign_date
--can you try this one.
WITH arrival_cluster_raw AS (
SELECT
routes.uc_id,
cg.cluster_id,
cg.cluster_centroid,
routes.imei,
routes.time_created::date AS campaign_date,
min(routes.time_created) AS m_per_imei_cluster
FROM
cluster_groups AS cg
JOIN routes ON routes.uc_id = cg.id --assume the way you want join.
GROUP BY
1,2,3,4,5
),
arrival_cluster_final AS (
SELECT
uc_id,
cluster_id,
cluster_centroid,
imei,
campaign_date,
date_trunc('second', (avg(m_per_imei_cluster) OVER w))
,count( CASE WHEN (avg(m_per_imei_cluster) OVER w) < m_per_imei_cluster THEN
1
ELSE
NULL
END) AS num_of_arrival_teams_before_avg_time
,count(
CASE WHEN (avg(m_per_imei_cluster) OVER w) > m_per_imei_cluster THEN
1
ELSE
NULL
END) AS num_of_arrival_teams_after_avg_time
FROM
arrival_cluster_raw
WINDOW w AS (PARTITION BY uc_id,
cluster_id,
cluster_centroid,
campaign_date))
SELECT * FROM arrival_cluster_final ORDER BY 1;
Need to plot data extracted for table into a pie-chart.
I am selecting data from a table to count tickets with different scenarios. I am able to simply select data to be plotted in excel.
But I need to select the same data in such a way that It can be plotted in pie-chart also.
SELECT Sum(CASE
WHEN Date(reportdate) < Date(current timestamp)
AND ( status NOT IN (SELECT value
FROM synonymdomain
WHERE maxvalue IN ( 'RESOLVED', 'CLOSED'
,
'REJECTED' )
AND domainid IN ( 'INCIDENTSTATUS'
)) )
AND incident.ir IS NOT NULL THEN 1
end) AS IMs_Balance_Carry_Forward,
( Sum(CASE
WHEN Date(reportdate) = Date(current timestamp)
AND ( status NOT IN (SELECT value
FROM synonymdomain
WHERE maxvalue IN (
'RESOLVED', 'CLOSED',
'REJECTED' )
AND domainid IN (
'INCIDENTSTATUS' )) )
AND ( incident.ir IS NOT NULL ) THEN 1
end) ) AS IM_Added_During_the_day,
from INCIDENT
Current Result:
IMS_BALANCE_CARRY_FORWARD IM_ADDED_DURING_THE_DAY
120 8
Required Result"
Column1 Column2
IMS_BALANCE_CARRY_FORWARD 120
IM_ADDED_DURING_THE_DAY 8
You want an unpivot capability, this has been answered here before. previous question and answer
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
I know that there's a better way to do what I'm trying to accomplish here. Though the query works I fear it's performance will suffer as the dataset's it is applied to grow.
I don't even necesarily need someone to rewrite what I have if they would just be willing to point me in the direction of the topic I should study I would greatly appreciate it.
What I'm trying to return with this query is a count of the number of records at or above a certain status.
Thanks in advance for your help!
SELECT
( SELECT count(*)
FROM TABLE1 c1
WHERE ( c1.U_KEY3 NOT LIKE 'z%' AND (c1.U_KEY1 = '' or c1.U_KEY1 IS NULL) )
) AS 'STATUS is EMPTY'
,
( SELECT count(*)
FROM TABLE1 c1
WHERE ( c1.U_KEY3 NOT LIKE 'z%' AND LEFT(c1.U_KEY1,2) >= '70' )
) AS 'STATUS > 70'
,
( SELECT count(*)
FROM TABLE1 c1
WHERE ( c1.U_KEY3 NOT LIKE 'z%' AND LEFT(c1.U_KEY1,2) >= '50' )
) AS 'STATUS > 50'
,
( SELECT count(*)
FROM TABLE1 c1
WHERE ( c1.U_KEY3 NOT LIKE 'z%' AND LEFT(c1.U_KEY1,2) >= '30' )
) AS 'STATUS > 30'
,
( SELECT count(*)
FROM TABLE1 c1
WHERE ( c1.U_KEY3 NOT LIKE 'z%' AND LEFT(c1.U_KEY1,2) >= '10' )
) AS 'STATUS > 10'
You could roll all the subqueries into a single query using a CASE statement:
SELECT
SUM(CASE WHEN c1.U_KEY1 = '' OR c1.U_KEY1 IS NULL THEN 1 ELSE 0 END) AS 'STATUS IS EMPTY',
SUM(CASE WHEN LEFT(c1.U_KEY1,2) >= '70' THEN 1 ELSE 0 END) AS 'STATUS > 70',
SUM(CASE WHEN LEFT(c1.U_KEY1,2) >= '50' THEN 1 ELSE 0 END) AS 'STATUS > 50',
SUM(CASE WHEN LEFT(c1.U_KEY1,2) >= '30' THEN 1 ELSE 0 END) AS 'STATUS > 30',
SUM(CASE WHEN LEFT(c1.U_KEY1,2) >= '10' THEN 1 ELSE 0 END) AS 'STATUS > 10'
FROM TABLE1 c1
WHERE c1.U_KEY3 NOT LIKE 'z%'
But this might not run as fast as the individual subqueries.
I would turn the question around like this:
DECLARE #t TABLE (Id INT, U_Key1 VARCHAR(4) null);
INSERT INTO #t (id,U_Key1)
VALUES
(1,null),
(2,'902'),
(3,'452'),
(4,'401'),
(5,'103'),
(6,'359'),
(7,'335'),
(8,'772'),
(9,'143'),
(10,'222'),
(11,'664'),
(12,'992'),
(13,'122'),
(14,'332'),
(15,'421'),
(16,'622'),
(17,'982'),
(18,'1234'),
(19,null),
(20,'012');
WITH A AS (
SELECT CAST(LEFT(U_Key1,2) AS INT) val FROM #t
), limits AS (
SELECT 10 limitval, 'Status >= 10' limittext
UNION ALL
SELECT 30 , 'Status >= 30'
UNION ALL
SELECT 50 , 'Status >= 50'
UNION ALL
SELECT 70 , 'Status >= 70'
), Counts AS (
SELECT 'Status is empty' Limittext, COUNT(id) Count FROM #t
WHERE U_Key1 IS null
UNION ALL
SELECT l.limittext, COUNT( A.val) Count FROM A
CROSS JOIN limits l
WHERE A.val >= l.limitval
GROUP BY l.limittext
)
SELECT * FROM Counts
That produces the result:
Status is empty 2
Status >= 10 17
Status >= 30 12
Status >= 50 6
Status >= 70 4
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