How to use max in with clause to get a single value and use this value in main query with null check - sql

I am unable to write this, please help. Below will give an idea of what I'm trying to achieve.
WITH monthly_data AS
(SELECT MAX(some_date) latest_dt FROM monthly_data
)
SELECT SUM(data)
FROM daily_data
WHERE (monthly_data.latest_dt IS NULL
OR daily_data.some_date > monthly_data.latest_dt)
table: monthly_data
id some_date
007 08-MAY-2018
table: daily_data
some_date data
07-MAY-2018 1
08-MAY-2018 1
09-MAY-2018 1
Expected result
Case 1: 1 row exist in table monthly_data.
Query should return 1.
Case 2: No rows exist in table montly_data.
Query should return 3.
The joins in the above query is incorrect but basically written to give you an idea of what I'm trying to do. Also, when I say no rows exist in table monthly_data, it is simplified explanation. There are other conditions in the actual query that filter out the data.
This has to go in a procedure
Edit
Thanks to #D-Shih I'm in a much better position where I started by using the exist clause query that he has provided.
On performance terms, can we write it in a faster way? Something that can evaluate to below would be fastest I believe
WITH CTE AS
( SELECT MAX(some_date) latest_dt FROM monthly_data
)
SELECT SUM(d.some_data)
FROM daily_data d
WHERE (d.some_date > '08-MAY-2018'
OR '08-MAY-2018' IS NULL)

If I understand correct.I think this will be work.
Due to you didn't provide some sample data and expect result.If that didn't your expect result,you can provide some sample data and expect result,I will edit my answer.
WITH CTE AS (
SELECT Max(some_date) latest_dt
FROM monthly_data
)
SELECT Sum(d.data)
FROM daily_data d
WHERE Exists (
SELECT 1
FROM CTE c
WHERE
d.some_date > c.latest_dt
OR
c.latest_dt IS NULL
)
Edit
You can try use CTE table JOIN on daily_data table
WITH CTE AS (
SELECT Max(some_date) latest_dt
FROM monthly_data
)
SELECT SUM(d.data)
FROM CTE c JOIN daily_data d
ON d.some_date > c.latest_dt OR c.latest_dt IS NULL;
sqlfiddle: http://sqlfiddle.com/#!4/33c64e/28

TRY THIS:
SELECT CASE WHEN SUM(CASE WHEN md.Sdate IS NOT NULL THEN 1 ELSE 0 END) > 0 THEN
SUM(CASE WHEN md.Sdate IS NOT NULL THEN 1 ELSE 0 END)
ELSE
SUM(CASE WHEN md.Sdate IS NULL THEN 1 ELSE 0 END)
END cnt
FROM daily_data dd
LEFT JOIN monthly_data md ON md.Sdate = dd.Sdate
....... {other conditions}

Related

SQL code to count only duplicates where all instances of the duplicate are null

I have a large data set with duplicate reference numbers (reference duplications range from 0 to 37 times). I want to count the number of references only where all instances are null in two columns. So using the table below, the code should return 1 because only Reference Code 3 has all null values, and the duplicates should only be counted once.
I would be grateful for any help.
This involves two steps: (1) isolate all the distinct pairs of values that only have null; (2) count each one once. One way to express this in a query is:
SELECT COUNT(*) FROM
(
SELECT refnum FROM #ref
GROUP BY refnum
HAVING MIN(colA) IS NULL
AND MIN(colB) IS NULL;
) AS x;
Use aggregation to get the codes:
select code
from t
group by code
having max(a) is null and max(b) is null;
If you want the count, use a subquery:
select count(*)
from (select code
from t
group by code
having max(a) is null and max(b) is null
) t;
With conditional aggregation:
select
refcode
from referencecodes
group by refcode
having sum(case when (a is null and b is null) then 0 else 1 end) = 0
The above will return the codes with only null values in a and b.
If you want the number of codes:
select count(r.refcode) from (
select
refcode
from referencecodes
group by refcode
having sum(case when (a is null and b is null) then 0 else 1 end) = 0
) r
Or with EXISTS:
select
count(distinct r.refcode)
from referencecodes r
where not exists (
select 1 from referencecodes
where (refcode = r.refcode) and (a is not null or b is not null)
)
See the demo

Trying to find unique records in a table that don't have a negating record

I have a table with a whole bunch of records.
table looks like this (simplified):
ID DoID DoQty DoType DoValue
1 17 1 Door 15
2 17 -1 Door -15
3 18 1 Window 75
4 19 1 Bed 125
5 19 1 Bed 134
so this is what I'd like to pull
ID DoId DoQty DoType DoValue
3 18 1 WIndows 75
4 19 1 Bed 125
5 19 1 Bed 134
I don't need DoID=17 because it has a 2nd line where DoQty is -1. SO that overall DoQty = 0. I only need records where there isn't a DoQty=-1. The problem here is that I do not want to group by DoID I want to be able to see the whole record line (no group by)
EDIT:
Unfortunately I might not have explained my question correctly. Basically, if I run the following query, i get the correct counts, however my goal is to get the details of each line.
SELECT t.DoID,
'Available' = Sum(t.DoQty)
From t
GROUP BY t.DoID
This gives me grouped results from which I can't do anything with.
As i understand you dont what to record where has any negative DoQty in any row. If it is correct, a possible solution is below,
SELECT t1.ID, t1.DoID, t1.DoQty, t1.DoType, t1.DoValue
FROM table t1
LEFT JOIN table t2 ON t2.DoQty < 0 AND t1.DoID = t2.DoID
WHERE t2.DoID IS NULL
We can use conditional aggregation here:
WITH cte AS (
SELECT DoID
FROM yourTable
GROUP BY DoID
HAVING SUM(CASE WHEN DoQty < 0 THEN 1 ELSE 0 END) = 0
)
SELECT *
FROM yourTable
WHERE DoID IN (SELECT DoID FROM cte);
This would return every DoID whose group of records does not have any DoQty values which are negative.
Is this what you want?
select t.*
from t
where not exists (select 1 from t t2 where t2.doid = t.doid and t2.doqty = - t.doqty);
This filters out rows where the "negative" value exists.
What I'm trying to do here is only pull up DoID's that don't have have a DoQty>0
Try this...
SELECT DoID
FROM table tbl
WHERE NOT EXISTS (
SELECT DoID FROM table WHERE DoQty <= 0 AND DoID = tbl.DoID
);
You can try the below:
With Agg AS
(
select DOID,sum(DoQty) as Qty from TableName
group by DOID having sum(DoQty)>0
)
select T.* from TableName T Inner Join Agg A
on T.DOID=A.DOID;
You seems want :
SELECT *, SUM(t.DoQty) OVER (PARTITION BY t.DoID) as Available
From t;

Check whether an employee is present on three consecutive days

I have a table called tbl_A with the following schema:
After insert, I have the following data in tbl_A:
Now the question is how to write a query for the following scenario:
Put (1) in front of any employee who was present three days consecutively
Put (0) in front of employee who was not present three days consecutively
The output screen shoot:
I think we should use case statement, but I am not able to check three consecutive days from date. I hope I am helped in this
Thank you
select name, case when max(cons_days) >= 3 then 1 else 0 end as presence
from (
select name, count(*) as cons_days
from tbl_A, (values (0),(1),(2)) as a(dd)
group by name, adate + dd
)x
group by name
With a self-join on name and available = 'Y', we create an inner table with different combinations of dates for a given name and take a count of those entries in which the dates of the two instances of the table are less than 2 units apart i.e. for each value of a date adate, it will check for entries with its own value adate as well as adate + 1 and adate + 2. If all 3 entries are present, the count will be 3 and you will have a flag with value 1 for such names(this is done in the outer query). Try the below query:
SELECT Z.NAME,
CASE WHEN Z.CONSEQ_AVAIL >= 3 THEN 1 ELSE 0 END AS YOUR_FLAG
FROM
(
SELECT A.NAME,
SUM(CASE WHEN B.ADATE >= A.ADATE AND B.ADATE <= A.ADATE + 2 THEN 1 ELSE 0 END) AS CONSEQ_AVAIL
FROM
TABL_A A INNER JOIN TABL_A B
ON A.NAME = B.NAME AND A.AVAILABLE = 'Y' AND B.AVAILABLE = 'Y'
GROUP BY A.NAME
) Z;
Due to the complexity of the problem, I have not been able to test it out. If something is really wrong, please let me know and I will be happy to take down my answer.
--Below is My Approch
select Name,
Case WHen Max_Count>=3 Then 1 else 0 end as Presence
from
(
Select Name,MAx(Coun) as Max_Count
from
(
select Name, (count(*) over (partition by Name,Ref_Date)) as Coun from
(
select Name,adate + row_number() over (partition by Name order by Adate desc) as Ref_Date
from temp
where available='Y'
)
) group by Name
);
select name as employee , case when sum(diff) > =3 then 1 else 0 end as presence
from
(select id, name, Available,Adate, lead(Adate,1) over(order by name) as lead,
case when datediff(day, Adate,lead(Adate,1) over(order by name)) = 1 then 1 else 0 end as diff
from table_A
where Available = 'Y') A
group by name;

T-Sql: turn multiple rows into one row

How does one turn these multiple rows into one row? N and Y are bool values.
Id IsPnt IsPms, IsPdt
1 N Y N
1 N Y N
1 Y N N
into this
Id IsPnt IsPms, IsPdt
1 Y Y N
Edit:
The query that produces the resultset looks like this
select b.id,
CASE mpft.PlanIndCd WHEN 'PBMN' THEN 1 ELSE 0 END AS IsPnt,
CASE mpft.PlanIndCd WHEN 'PBMT' THEN 1 ELSE 0 END AS IsPbt,
CASE mpft.PlanIndCd WHEN 'PBMS' THEN 1 ELSE 0 END AS IsPms
from vw_D_SomveViewName pb
-- bunch of joins
where mpft.PlanIndCd in ('HANR', 'PBMN','PBMT','PBMS','HAWR')
You can simply use MAX() on this if the values are really Y and N only.
SELECT ID, MAX(IsPnt) IsPnt, MAX(IsPms) IsPms, MAX(IsPdt) IsPdt
FROM tableName
GROUP BY ID
UPDATE 1
SELECT b.id,
MAX(CASE mpft.PlanIndCd WHEN 'PBMN' THEN 1 ELSE 0 END) AS IsPnt,
MAX(CASE mpft.PlanIndCd WHEN 'PBMT' THEN 1 ELSE 0 END) AS IsPbt,
MAX(CASE mpft.PlanIndCd WHEN 'PBMS' THEN 1 ELSE 0 END) AS IsPms
FROM vw_D_SomveViewName pb
-- bunch of joins
WHERE mpft.PlanIndCd in ('HANR', 'PBMN','PBMT','PBMS','HAWR')
GROUP BY b.ID
Will this work?
select
id,
max(IsPnt),
max(IsPms),
max(IsPdt)
from
table
GROUP BY
id
After the edit of your question, you can simply use the PIVOT table operator directly instead of using the MAX expression, something like:
SELECT
Id,
PBMN AS IsPnt,
PBMT AS IsPbt,
PBMS AS IsPms
FROM
(
SELECT
id,
mpft.PlanIndCd,
ROW_NUMBER() OVER(PARTITION BY id
ORDER BY ( SELECT 1)) AS RN
from vw_D_SomveViewName pb
-- bunch of joins
where mpft.PlanIndCd in ('HANR', 'PBMN','PBMT','PBMS','HAWR')
) AS t
PIVOt
(
MAX(RN)
FOR PlanIndCd IN ([PBMN], [PBMT], [PBMS])
) AS p;
You can see it in action in the following demo example:
Demo on SQL Fiddle
select Id, MAX(IPnt), MAX(IsPms), MAX(IsPdt)
from table etc

How do I use the value from row above when a given column value is zero?

I have a table of items by date (each row is a new date). I am drawing out a value from another column D. I need it to replace 0s though. I need the following logic: when D=0 for that date, use the value in column D from the date prior.
Actually, truth be told, I need it to say, when D is 0, use the value from the latest date where D was not a 0, but the first will get me most of the way there.
Is there a way to build this logic? Maybe a CTE?
Thank you very much.
PS I'm using SSMS 2008.
EDIT: I wasn't very clear at first. The value I want to change is not the date. I want change the value in D with the latest non-zero value from D, based on date.
May be the following query might help you. It uses the OUTER APPLY to fetch the results. Screenshot #1 shows the sample data and query output against the sample data. This query can be written better but this is what I could come up with right now.
Hope that helps.
SELECT ITM.Id
, COALESCE(DAT.New_D, ITM.D) AS D
, ITM.DateValue
FROM dbo.Items ITM
OUTER APPLY (
SELECT
TOP 1 D AS New_D
FROM dbo.Items DAT
WHERE DAT.DateValue < ITM.DateValue
AND DAT.D <> 0
AND ITM.D = 0
ORDER BY DAT.DateValue DESC
) DAT
Screenshot #1:
UPDATE t
Set value = SELECT value
FROM table
WHERE date = (SELECT MAX(t1.date)
FROM table t1
WHERE t1.value != 0
AND t1.date < t.date)
FROM table t
WHERE t.value = 0
You could maybe something like this as part of an update script...
SET myTable.D = (
SELECT TOP 1 myTable2.D
FROM myTable2
WHERE myTable2.myDateField < myTable.myDateField
AND myTable2.D != 0
ORDER BY myTable2.myDateField DESC)
That's assuming that you want to actually update the data though rather than just replace the values for the purpose of a select query.
How about:
SELECT
i.ID,
i.DateValue,
D = CASE WHEN I.D <> 0 THEN I.D ELSE X.D END
FROM
Items I
OUTER APPLY (
SELECT TOP 1 S.D
FROM Items S
WHERE S.DATEVALUE < I.DATEVALUE AND S.D <> 0
ORDER BY S.DATEVALUE DESC
) X
SELECT t.id,
CASE WHEN t.D = 0 THEN t0.D
ELSE t.D END
FROM table AS t
LEFT JOIN table AS t0
ON t0.time =
(
SELECT MAX(time) FROM t0
WHERE t0.time < t.time
AND t0.D != 0
)
or if you want to avoid aggregates entirely,
SELECT t.id,
CASE WHEN t.D = 0 THEN t0.D
ELSE t.D END
FROM table AS t
LEFT JOIN table AS t0
ON t0.time < t.time
LEFT JOIN table AS tx
ON tx.time > t0.time
WHERE t0.D != 0
AND tx.D != 0
AND tx.id IS NULL -- i.e. there isn't any