T SQL Count and Group by calculable column - sql

This code
DECLARE #SNH TABLE
(
cntDATE date,
cntQUEUE varchar(10),
[cntINKTONERBLACK] int
)
INSERT INTO #SNH (cntDATE, cntQUEUE, [cntINKTONERBLACK])
VALUES ('2001-04-04', 'Queue01', 3),
('2001-04-05', 'Queue01', 1),
('2001-04-06', 'Queue01', 100)
SELECT TOP 5
[cntQUEUE] AS cntqueue,
[cntdate],
[cntINKTONERBLACK],
(CASE
WHEN LAG(cntinktonerblack) OVER (PARTITION BY cntqueue ORDER BY cntqueue, cntdate) < cntinktonerblack
THEN 1
ELSE 0
END) AS signalcolumn
FROM
#SNH
WHERE
[cntINKTONERBLACK] IS NOT NULL
ORDER BY
cntqueue, cntDATE ASC
gives the following table
cntqueue
cntdate
cntINKTONERBLACK
signalcolumn
Queue01
2001-04-04
3
0
Queue01
2001-04-05
1
0
Queue01
2001-04-06
100
1
Is there a way to count '1' in signal column and group 1st column to have?
cntqueue
NumberOfJumps
Queue01
1

You can use a subquery:
select cntqueue, sum(signalcolumn)
from (select cntQUEUE,
(case when lag(cntinktonerblack) over (partition by cntqueue order by cntqueue, cntdate) < cntinktonerblack
then 1 else 0
end) as signalcolumn
from [watchdocstatsSU].[dbo].[queuescounters]
where [cntINKTONERBLACK] is NOT null
) q
group by cntqueue
order by cntqueue;

Related

CTE function with insert statement

I have 2 queries and I need to combine them into one query with an insert statement.
This is my first query that already has an insert statement:
with q as (
select s.department
,s.months
,s.years
,count(case when s.sum_lost_time >='10:00:00' then NAME end) as RTOTALLOSTTIME
,count(case when s.sum_ot >='20' then NAME end) as ROT
from (select MONTH(STATUSIN) as [months]
,YEAR(STATUSIN) as [years]
,NIP
,NAME
,DEPARTMENT
,convert(varchar,dateadd(second,sum(datediff(second,'00:00:00',cast(TOTALLT as time))),0),108) as sum_lost_time
,SUM(CAST(OT AS FLOAT)) as sum_ot
from SUMMARYDATA b
group by MONTH(STATUSIN)
,YEAR(STATUSIN)
,NIP
,NAME
,DEPARTMENT
)s
group by s.department
,s.months
,s.years
)
INSERT INTO REPORTDATA(DEPARTMENT,MONTHS,YEARS,RTOTALLOSTTIME,ROT)
SELECT DEPARTMENT,MONTHS,YEARS,RTOTALLOSTTIME,ROT
FROM q
This is the result from first query in table REPORTDATA:
And this is my second query.
WITH cte AS
(
SELECT DISTINCT [NAME], DEPARTMENT, MONTH(STATUSIN) [MONTH], YEAR(STATUSIN) [YEAR],
SUM(CASE WHEN LATECOME = '00:00:00' THEN 0 ELSE 1 END) OVER(PARTITION BY [NAME], DEPARTMENT, MONTH(STATUSIN), YEAR(STATUSIN)) Total
,SUM(CASE WHEN EARLYLEAVE = '00:00:00' THEN 0 ELSE 1 END) OVER(PARTITION BY [NAME], DEPARTMENT, MONTH(STATUSIN), YEAR(STATUSIN)) TotalEarlyLeave
FROM SUMMARYDATA
)
SELECT SUM(CASE WHEN TOTAL > 2 THEN 1 ELSE 0 END) LATECOME,
SUM(CASE WHEN TotalEarlyLeave > 1 THEN 1 ELSE 0 END) EARLYLEAVE
FROM cte
GROUP BY DEPARTMENT, [MONTH], [YEAR]
And this is the result from second query:
I want to place it into my first query but I don't know how to combine it into one in insert statement. Can anyone solve my problems?
This is the sample to my first query: Count summary records per month with conditional SQL
and this is the sample to second query: Count records per month with condition in SQL Server
It's easy if you concatenate your queries as multiple CTEs, and finally JOIN them.
Like this :
;
with cte1 as (
select s.department
,s.months
,s.years
,count(case when s.sum_lost_time >='10:00:00' then NAME end) as RTOTALLOSTTIME
,count(case when s.sum_ot >='20' then NAME end) as ROT
from (select MONTH(STATUSIN) as [months]
,YEAR(STATUSIN) as [years]
,NIP
,NAME
,DEPARTMENT
,convert(varchar,dateadd(second,sum(datediff(second,'00:00:00',cast(TOTALLT as time))),0),108) as sum_lost_time
,SUM(CAST(OT AS FLOAT)) as sum_ot
from SUMMARYDATA b
group by MONTH(STATUSIN)
,YEAR(STATUSIN)
,NIP
,NAME
,DEPARTMENT
)s
group by s.department
,s.months
,s.years
),
cte2 as (
SELECT DISTINCT [NAME], DEPARTMENT, MONTH(STATUSIN) [MONTH], YEAR(STATUSIN) [YEAR],
SUM(CASE WHEN LATECOME = '00:00:00' THEN 0 ELSE 1 END) OVER(PARTITION BY [NAME], DEPARTMENT, MONTH(STATUSIN), YEAR(STATUSIN)) Total
,SUM(CASE WHEN EARLYLEAVE = '00:00:00' THEN 0 ELSE 1 END) OVER(PARTITION BY [NAME], DEPARTMENT, MONTH(STATUSIN), YEAR(STATUSIN)) TotalEarlyLeave
FROM SUMMARYDATA
),
cte3 as (
SELECT DEPARTMENT, [MONTH], [YEAR], SUM(CASE WHEN TOTAL > 2 THEN 1 ELSE 0 END) LATECOME,
SUM(CASE WHEN TotalEarlyLeave > 1 THEN 1 ELSE 0 END) EARLYLEAVE
FROM cte2
GROUP BY DEPARTMENT, [MONTH], [YEAR]
)
INSERT INTO REPORTDATA (DEPARTMENT, MONTHS, YEARS, RTOTALLOSTTIME, ROT, RLATECOME, REARLYLEAVE)
SELECT cte1.DEPARTMENT, cte1.MONTHS, cte1.YEARS, cte1.RTOTALLOSTTIME, cte1.ROT,
cte3.LATECOME, cte3.EARLYLEAVE
FROM cte1
LEFT JOIN cte3 ON cte3.DEPARTMENT = cte1.DEPARTMENT and cte3.[MONTH] = cte1.[MONTH] and cte3.[YEAR] = cte1.[YEAR]

sql purchase items

I need a stored procedure for solve this problem. I have table with name Items With Values
id qty
1 5
2 10
3 15
If a parameter value = 10, and the table will be
id qty
1 0
2 5
3 15
If your dbms supports window functions (ms sql server 2012+ is used below):
declare #prm int = 10;
select id, qty
, case
when qty + tot <= #prm then 0
when tot > #prm then qty
else (qty + tot) - #prm
end currQty
from (
select id, qty, coalesce (sum(qty) over(order by id rows between unbounded preceding and 1 preceding), 0) tot
from
-- your table here
(values
(1,5 )
,(2,10)
,(3,15)
) tbl (id,qty)
) t;
Basically, you want to use a cumulative sum for this purpose. The rest is just arithmetic. I like to phrase this as:
select t.*,
(case when running_qty <= #parameter
then 0
when running_qty - qty <= #parameter
then running_qty - #parameter
else qty
end) as new_qty
from (select t.*,
sum(qty) over (order by id) as running_qty
from t
) t;
Here is a db<>fiddle.

Categorize Overlap Type - Oracle

I've been able to use How do I find the total number of used days in a month? to answer how many TOTAL days we've had cats and dogs which is helpful but I need to know how many days we had:
Cats only: 4
Dogs only: 5
Both: 6
Thank you in advance!
CREATE TABLE "ANIMALGUESTS"
( "ID" NUMBER,
"GUESTNAME" VARCHAR2(20 BYTE),
"GUESTTYPE" VARCHAR2(20 BYTE),
"CHECKIN" DATE,
"CHECKOUT" DATE
);
Insert into ANIMALGUESTS (ID,GUESTNAME,GUESTTYPE,CHECKIN,CHECKOUT) values (1,'Tom','Cat',to_date('01-JAN-19','DD-MON-RR'),to_date('10-JAN-19','DD-MON-RR'));
Insert into ANIMALGUESTS (ID,GUESTNAME,GUESTTYPE,CHECKIN,CHECKOUT) values (2,'Spike','Dog',to_date('03-JAN-19','DD-MON-RR'),to_date('05-JAN-19','DD-MON-RR'));
Insert into ANIMALGUESTS (ID,GUESTNAME,GUESTTYPE,CHECKIN,CHECKOUT) values (3,'Spike','Dog',to_date('08-JAN-19','DD-MON-RR'),to_date('12-JAN-19','DD-MON-RR'));
Insert into ANIMALGUESTS (ID,GUESTNAME,GUESTTYPE,CHECKIN,CHECKOUT) values (4,'Cherie','Cat',to_date('07-JAN-19','DD-MON-RR'),to_date('09-JAN-19','DD-MON-RR'));
Insert into ANIMALGUESTS (ID,GUESTNAME,GUESTTYPE,CHECKIN,CHECKOUT) values (5,'Tyke','Dog',to_date('10-JAN-19','DD-MON-RR'),to_date('15-JAN-19','DD-MON-RR'));
Using conditional aggregation and inline calendar table:
WITH cte AS (
SELECT DATE '2019-01-01' + rownum -1 dt FROM DUAL CONNECT BY ROWNUM < 366
)
SELECT DISTINCT
SUM(CASE WHEN COUNT(DISTINCT GUESTTYPE)=2 THEN 1 END) OVER() AS both,
SUM(CASE WHEN COUNT(DISTINCT GUESTTYPE)=1 AND MIN(GUESTTYPE)='Cat' THEN 1 END) OVER() AS cats_only,
SUM(CASE WHEN COUNT(DISTINCT GUESTTYPE)=1 AND MIN(GUESTTYPE)='Dog' THEN 1 END) OVER() AS dogs_only
FROM cte c
LEFT JOIN "ANIMALGUESTS" a ON c.dt BETWEEN a.CHECKIN AND a.CHECKOUT
GROUP BY dt;
db<>fiddle demo
Oracle 12c supports recursive CTEs, so you can expand the data and then aggregate:
with cte as (
select checkin as dt, checkout, guesttype
from ANIMALGUESTS
union all
select dt + 1, checkout, guesttype
from cte
where dt < checkout
)
select sum(case when cats > 0 and dogs > 0 then 1 else 0 end) as both,
sum(case when cats > 0 and dogs = 0 then 1 else 0 end) as cats_only,
sum(case when cats = 0 and dogs > 0 then 1 else 0 end) as dogs_only
from (select dt, sum(case when guesttype = 'Cat' then 1 else 0 end) as cats,
sum(case when guesttype = 'Dog' then 1 else 0 end) as dogs
from cte
group by dt
) cte;
This generates the result set as columns in a row, rather than separate rows.

SSRS: how to get top 3 in order Z to A

I try to get in my diagram the top 3 of the worst value in SSRS:
my Code:
SELECT *
FROM (
Select top 3
intervaldate as Datum
,Name
,teamname as Team
,SUM(case when CounterName = 'Blown away' then calculationUnits else 0 end) as Blown
,Sum(case when CounterName = 'Thrown away' then calculationUnits else 0 end) as Thrown
,Sum(case when CounterName = 'total' then calculationUnits else 0 end) as Total
from Counting
where IntervalDate >= dateadd(day,datediff(day,1,GETDATE()),0)
AND IntervalDate < dateadd(day,datediff(day,0,GETDATE()),0)
and Name in (Select SystemID from tSystemView where SystemViewID = 2)
group by intervaldate, teamName, Name
) c
Expression of the diagram:
=Sum(Fields!Blown.Value + Fields!Thrown.Value) / Sum(Fields!Total.Value) * 100
And I sorted it from highest to lowest
But it does not show me the right order.
If I choose every "Name" then it shows me other value then the top 3:
all Names with value:
top 3:
It's because your top 3 statement is in the SQL while your sort is in the report. Without an order by SQL picks the top 3 random records. Also, unless there is more SQL you are not showing, the outer select is unnecessary. Add an order by <column> desc below your group by.
with Calcs as
(
select intervaldate as Datum,
Name,
TeamName,
SUM(case when CounterName = 'Blown away' then calculationUnits else 0 end) as Blown,
Sum(case when CounterName = 'Thrown away' then calculationUnits else 0 end) as Thrown,
Sum(case when CounterName = 'total' then calculationUnits else 0 end) as Total
from Counting
where IntervalDate >= dateadd(day,datediff(day,1,GETDATE()),0)
AND IntervalDate < dateadd(day,datediff(day,0,GETDATE()),0)
and Name in (Select SystemID from tSystemView where SystemViewID = 2)
group by intervaldate, teamName, Name
)
select b.*
from
(
select a.*, row_number() over (order by (Blown + Thrown)/Total desc) as R_Ord -- Change between ASC/DESC depending on needs
from Calcs a
) b
where R_Ord <=3

SemanticException Failed to breakup Windowing invocations into Groups. At least 1 group must only depend on input columns

The below query is working fine in Oracle but it is not working in hive.
SELECT Q.tm_mo_id,
'1380' AS mrc_cd,
NVL (R.itm_profit_ctr_cd, '99') AS profit_center_cd,
MAX(CASE R.itm_profit_ctr_cd
WHEN NULL THEN 'UNASSIGN PROFIT CNTR'
ELSE R.itm_profit_ctr_ds
END) profit_center_desc,
SUM(Q.bp_grs_quota_am) AS mth_bp_plan_gts_am_usd,
SUM(Q.grs_quota_am) AS mth_ju_plan_gts_am_usd
FROM v_l_0002_gb_gds_us_quota_v_1 Q
LEFT JOIN
(SELECT * FROM
(SELECT ph_dtl_id,
itm_profit_ctr_cd,
MIN (itm_profit_ctr_ds) AS itm_profit_ctr_ds,
ROW_NUMBER () OVER (
PARTITION BY ph_dtl_id
ORDER BY COUNT(CASE profit_ctr_cd
WHEN 'JNJDUMMY' THEN NULL
WHEN '99' THEN NULL
ELSE profit_ctr_cd
END) DESC,
itm_profit_ctr_cd ASC) rn
FROM v_l_0002_gb_gds_us_sku_to_profit_center_lookup_v_1
GROUP BY ph_dtl_id,
itm_profit_ctr_cd) E
WHERE rn = 1 ) R
ON (Q.ph_dtl_id = R.ph_dtl_id)
WHERE SUBSTR (Q.tm_mo_id, 1, 4) = '2016'
GROUP BY Q.tm_mo_id,
NVL(R.itm_profit_ctr_cd, '99')