Nested Case Statement - sql-server-2008

I am writing a case statement to fetch results every 2 hours. I need to sum all the results but exclude the following timestamps : 2016-01-08 00:00:00.000 (all the ones that have basically no timestamp in the database.
My query looks like this:
select
sum(
CASE WHEN (End_Trailer_Break >= dateadd(hour, datediff(hour, 0, DATEADD(HOUR, -10, GETDATE())), 0) and End_Trailer_Break < dateadd(hour, datediff(hour, 0, DATEADD(HOUR, -8, GETDATE())), 0))
THEN convert(int,replace (Tonnage, ',',''))
ELSE 0 END
) AS 'Tonnage'
from pm_inbound
I think I need to add this somewhere as a nested case statement to exclude the 00:00 timestamps:
REPLACE(CONVERT(CHAR(5),DATEADD(hour, DATEDIFF(hour, 0, End_Trailer_Break), 0) ,8),'00:00','')
Thank you

Related

MS SQL Server Query Date functions to MySQL

I have this MS SQL Server query:
SELECT DATEPART(MONTH, si.score_date),
MAX(si.score_value)
FROM score_info AS si
WHERE si.score_date >= DATEADD(MONTH, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
GROUP BY DATEPART(MONTH, si.score_date);
Now I'm having a hard time converting this query to MySQL especially this part:
DATEADD(MONTH, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
So far here's what I've converted from MS SQL Server query to MySQL query:
DATEPART(MONTH, si.score_date)
to
EXTRACT(MONTH FROM si.score_date)
Please help me as I'm on my learning stage. Thank you so much.
This T-SQL expression:
DATEADD(MONTH, -3, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
Gives you the first day of the month, 3 months ago (as of today March 30th, that's December 1st).
In MySQL you can get the same result like so:
DATE_FORMAT(CURRENT_DATE, '%Y-%m-01') - INTERVAL 3 MONTH
Also, EXTRACT(MONTH FROM si.score_date) can be shorten as MONTH(si.score_date) (the MONTH() function exists in both MySQL and TSQL, by the way). But note that presumably, you want to keep the year part as well, in case your data spreads over severl year.
I would write your query as:
SELECT
DATE_FORMAT(si.score_date, '%Y-%m-01') year_month,
MAX(si.score_value) max_score
FROM score_info AS si
WHERE si.score_date >= DATE_FORMAT(CURRENT_DATE, '%Y-%m-01') - INTERVAL 3 MONTH
GROUP BY DATE_FORMAT(si.score_date, '%Y-%m-01'));

Laravel - Query for Aging Report using Laravel

I have MySQL query that I want to convert to Laravel.
SELECT client_id,
DATEDIFF(CURDATE(), due_date) AS days_past_due,
SUM(IF(days_past_due = 0, amount_due, 0)),
SUM(IF(days_past_due BETWEEN 1 AND 30, amount_due, 0)),
SUM(IF(days_past_due BETWEEN 31 AND 60, amount_due, 0)),
SUM(IF(days_past_due BETWEEN 61 AND 90, amount_due, 0)),
SUM(IF(days_past_due > 90, amount_due, 0))
FROM invoices
GROUP BY client_id
I want to create a current,30, 60, 90, day aging reports in Matrix Format using Laravel query.
For example,
ClientName Current 1-30 31-60 >90 Total
AAA 3000 1500 4500
BBB 2000 200 2200
TOTAL 3000 3500 200 6700
I want to get the report like this. when user enters the date, it should check with duedate. when entered date is > due_date, get the aging days.
if aging agin days is today then get netAnmount and display in current column,
if difference is 1-30 days then next column...etc...
how to get query for this?
I use subQuery in Laravel maybe can help you.
$invoice = Invoice::select(\DB::raw('ledgers.id,invoices.invoice_no,invoices.invoice_date,invoices.invoice_due,invoices.invoice_balance,DATEDIFF("'.$request->input('to_date').'", invoices.invoice_date) AS days_past_due'))
->join('quotations','quotations.id','=','invoices.quotation_id')
->join('ledgers','ledgers.id','=','quotations.ledger_id')
->where('invoices.invoice_date','<=',$request->input('to_date'))
->whereNotIn('invoices.status',[1,2]);
$agingReport = Ledger::select(\DB::raw('a.id,ledgers.name,a.invoice_no,a.invoice_date,a.invoice_due,a.invoice_balance,a.days_past_due,CASE WHEN a.days_past_due =0 then a.invoice_balance else 0 end as month,
CASE WHEN a.days_past_due >0 and a.days_past_due <= 30 then a.invoice_balance else 0 end as aging30days,
CASE WHEN a.days_past_due >30 and a.days_past_due <= 60 then a.invoice_balance else 0 end as aging60days,
CASE WHEN a.days_past_due >60 and a.days_past_due <= 90 then a.invoice_balance else 0 end as aging90days,
CASE WHEN a.days_past_due >90 then a.invoice_balance else 0 end as more30days'))
->from(\DB::raw('('.$invoice->toSql().') as a '))
->mergeBindings($invoice->getQuery())
->join('ledgers','ledgers.id','=','a.id')
->get();
return response()->json($agingReport);

Getting the month to show date name rather than number when pulling each month in the year

I am pulling data that lists each month of the year but the month column states the first day of each year, how can I make this show the full month name?
Here is some of what I have. I read similar questions and tried to add in what it stated everywhere but I couldn't get it work, help?
SELECT a.MonthDate
,Sum(a.ScrapPcs) / (Sum(a.GrossPcs)*1.00) As ScrapPct
,0.05 As ScrapTarget
,sum (a.GrossPcs) As 'Total Parts Cast'
,sum (a.ScrapPcs) as 'Total Parts Scrap'
,CASE
WHEN Sum(a.ScrapPcs) / (Sum(a.GrossPcs)*1.00) <= 0.05 THEN 1
WHEN Sum(a.ScrapPcs) / (Sum(a.GrossPcs)*1.00) >= 0.9*.05 THEN -1
ELSE 0
END
AS Status
FROM
(
SELECT DATEADD(month, DATEDIFF(month, 0, b.CreationProdDate), 0) As MonthDate
,Count(b.BOOKING_ID) As ScrapPcs
, 0 As GrossPcs
FROM dbo.CPC_BOOKING b
WHERE b.CreationProdDate Between DATEADD(yy, DATEDIFF(yy, 0, GetDate()), 0) AND DateAdd("d", -1, GetDate())
and CPC_BookingTyp_ID in (2,8)
and ManufacturingPlant in (90002604,90017699, 90017705)
GROUP BY DATEADD(month, DATEDIFF(month, 0, b.CreationProdDate), 0)
UNION ALL
SELECT DATEADD(month, DATEDIFF(month, 0, n.ProductionDate), 0) As MonthDate
,0 As ScrapPcs
,Sum(n.Quantity) As GrossPcs
FROM [NORIS].[dbo].[MDL_Data_Ultimate] n
WHERE n.ProductionDate Between DATEADD(yy, DATEDIFF(yy, 0, GetDate()), 0) AND DateAdd("d", -1, GetDate())
and n.ManufacturingPlantGroup = 1
GROUP BY DATEADD(month, DATEDIFF(month, 0, n.ProductionDate), 0)
) a
group by a.MonthDate
Thanks in advance, anything helps
For MySQL:
https://www.w3resource.com/mysql/date-and-time-functions/mysql-monthname-function.php
Use the MONTHNAME function as per the example on that webpage.
SELECT MONTHNAME(a.MonthDate)
For MS SQL Server:
If you want the month name use this in the derived table:
SELECT datename(month,DATEADD(month, DATEDIFF(month, 0, b.CreationProdDate), 0)) As MonthDate
That is, you want to apply the datename(month, date)function to the first column of both unioned queries.

SQL to show min,max during timerange where name =(x)

Im trying to establish a basic report function.
The tables contain basic columns like this
ID, timestamp, value, key, Query, JSON
The only unique identifier is in the key colum
Theres half a million rows
I'd like it to report back this basically
SELECT min(value) as begin, max(value) as end FROM `key`WHERE NAME='Key1'
TIMERANGE='LastMonth'
Could someone please assist with the syntax of this or the concepts im missing
Thankyou and much appreciated
Try this
SELECT min(value) as begin, max(value) as end FROM `key`
WHERE NAME='Key1' and
timestamp>=date_add(current_date(),interval -1 month) and timestamp<=current_date()
SELECT min(value) as begin, max(value) as end FROM `key`
WHERE ID='Key1'
AND timestamp >= DATEADD(month, DATEDIFF(month, -1, getdate()) - 2, 0)
AND timestamp <= DATEADD(ss, -1, DATEADD(month, DATEDIFF(month, 0, getdate()), 0))
OR
SELECT ID, min(value) as begin, max(value) as end FROM `key`
WHERE timestamp >= DATEADD(month, DATEDIFF(month, -1, getdate()) - 2, 0)
AND timestamp <= DATEADD(ss, -1, DATEADD(month, DATEDIFF(month, 0, getdate()), 0))
GROUP BY ID

Get MAX minutes from query in SQL Server

I have a query that gets all the records for today. With the query below I get the difference from the time a ticket was issued till the current time. This gets the total waiting time.
I want to get the MAXWaitTime from my query result.
SELECT
DATEDIFF(minute, Issued, GETDATE()) AS MaxWaitTime
FROM
tblData
WHERE
(DATEADD(day, DATEDIFF(day, 0, Issued), 0) = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
This works fine I get the minutes back but for several records. I only want the highest.
My result:
32
50
25
I want the result to be the highest only:
50
You need to use the max function to get the highest value. Check this link
SELECT Max(DATEDIFF(minute,Issued,GETDATE()))AS MaxWaitTime
from tblData
WHERE
(DATEADD(day, DATEDIFF(day, 0, Issued), 0) = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))
Try Following Query :
SELECT max(DATEDIFF(minute,Issued,GETDATE())) AS MaxWaitTime
from tblData
WHERE (DATEADD(day, DATEDIFF(day, 0, Issued), 0) = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0))