awbno byhub entrydatetime uplopadtime
111 ho 2017-01-01 10:10:13.000 2017-01-01 10:10:13.000
222 ho 2017-01-01 18:10:13.00 2017-01-02 10:10:13.000
333 ho 2017-01-01 13:10:13.000 2017-01-03 10:10:13.000
444 ho 2017-01-01 10:10:13.000 2017-01-05 10:10:13.000
I would like to output like this way by substracting entrydatetime from uploadingdatetime:
byhub total_awbno sameday oneday twoday morethan_two_day
ho 4 1 1 1 1
I used this Query but not found right solution:-
select byhub ,
COUNT(awbno),
count(case when (datediff(day,uplopadtime,EntryDateTime)=0) then 1 end ),
count(case when (datediff(day,uplopadtime,EntryDateTime)=1) then 1 end ),
count(case when (datediff(day,uplopadtime,EntryDateTime)=2) then 1 end ),
count(case when (datediff(day, uplopadtime,EntryDateTime)>2) then 1 end )
from MyTable
group by byhub
The output of my query is:
ho 4 1 0 0 0
datediff() function in MySQL has only 2 parameters: 2 date values. The function you are looking for is TIMESTAMPDIFF() and you also need to reverse the order of the fields in the parameter list if you would like to substract entrydatetime from uploadingdatetime:
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns datetime_expr2 − datetime_expr1, where datetime_expr1 and
datetime_expr2 are date or datetime expressions. One expression may be
a date and the other a datetime; a date value is treated as a datetime
having the time part '00:00:00' where necessary. The unit for the
result (an integer) is given by the unit argument. The legal values
for unit are the same as those listed in the description of the
TIMESTAMPADD() function.
select byhub ,
COUNT(awbno),
count(case when timestampdiff(day,EntryDateTime,uplopadtime)=0 then 1 end ),
count(case when timestampdiff(day,EntryDateTime,uplopadtime)=1 then 1 end ),
count(case when timestampdiff(day,EntryDateTime,uplopadtime)=) then 1 end ),
count(case when timestampdiff(day,EntryDateTime,uplopadtime)>2 then 1 end )
from MyTable
group by byhub
timestampdiff(day,EntryDateTime,uplopadtime) is the same as datediff(EntryDateTime,uplopadtime)
Try this:
SELECT byhub,
COUNT(awbno) AS total_awbno,
COUNT(CASE WHEN days_diff = 0 THEN 1 END) AS sameday,
COUNT(CASE WHEN days_diff = 1 THEN 1 END) AS oneday,
COUNT(CASE WHEN days_diff = 2 THEN 1 END) AS twoday,
COUNT(CASE WHEN days_diff > 2 THEN 1 END) AS morethan_two_day
FROM (
SELECT awbno, byhub, datediff(uplopadtime,EntryDateTime) AS days_diff
FROM mytable) AS t
GROUP BY byhub;
Demo here
Check Bellow
select byhub ,
COUNT(awbno),
sum(case when (datediff(uplopadtime,EntryDateTime)=0) then 1 else 0 end ),
sum(case when (datediff(uplopadtime,EntryDateTime)=1 or datediff(uplopadtime,EntryDateTime)=-1) then 1 else 0 end ),
sum(case when (datediff(uplopadtime,EntryDateTime)=2 or datediff(uplopadtime,EntryDateTime)=-2) then 1 else 0 end ),
sum(case when (datediff(uplopadtime,EntryDateTime) > 2 or datediff(uplopadtime,EntryDateTime) < -2) then 1 else 0 end )
from MyTable
group by byhub
Related
I'm trying to learn sql query and i want to solve the following problem.
Assume the table as follow:
id
schoolname
totalA
totalB
grade
1
school A
5
5
1
2
school A
5
5
2
3
school B
5
5
1
4
school B
5
5
2
Select schoolname
SUM(CASE WHEN (grade='1' ) THEN totalA ELSE 0 END) AS t1A,
SUM(CASE WHEN (grade='1' ) THEN totalB ELSE 0 END) AS t1B,
SUM(CASE WHEN (grade='2' ) THEN totalA ELSE 0 END) AS t2A,
SUM(CASE WHEN (grade='2' ) THEN totalB ELSE 0 END) AS t2B,
I would like to know if it is possible to add both totalA and B in one case condition.
I tried
Select schoolname
CASE WHEN (grade='1' ) THEN SUM(totalA+totalB) ELSE 0 END AS Grade 1,
CASE WHEN (grade='2' ) THEN SUM(totalA+totalB) ELSE 0 END AS Grade 2,
From school
Group By schoolname
But it give me error.
I want to achieve the following:
schoolname
grade 1
grade 2
School A
10
10
School B
10
10
Yes it is possible by group by query of MySQL in the same table.
For that you need to use this type of query:
SELECT schoolname,
SUM(CASE WHEN (grade = 1) THEN totalA + totalB ELSE 0 END) AS grade_1,
SUM(CASE WHEN (grade = 2) THEN totalA + totalB ELSE 0 END) AS grade_2
FROM school
GROUP BY schoolname
So.. here is the thing.. Im trying to get a report based on this table on Mysql.
Table have these columns
statusvalue submitdate employeeNumber
2 2016-11-17 17:49:05 2
1 2016-11-17 17:49:11 4
3 2016-11-17 17:49:16 4
4 2016-11-17 17:50:58 2
5 2016-11-17 17:51:07 5
Status 0 = Pending
1= Started
2=inprogress
3= cancelled
4= terminated
5=unknown
now i need to select data as below
date day pending started inprogress cancelled terminated total
2017-04-17 Monday 0 1 4 0 1 6
2017-04-16 Sunday 0 1 4 0 1 6
so far i can get the date and the day
select date(submitdate) as subdate, case weekday(date(submitdate))
WHEN 0 then 'PENDING'
WHEN 1 then 'STARTED'
WHEN 2 then 'INPROGRESS'
WHEN 3 then 'CANCELLED'
WHEN 4 then 'TERMINATED'
WHEN 5 then 'UNKNOWN' END as submitdate
from tb_status t1 where employeenumber=15 group by subdate order by subdate ;
however not quite sure how to do a count based on status.. any help would be greatly appreciated.
You just need a basic pivot query here. Aggregate over the submission date, and then tally the various types of status as you go along.
SELECT
DATE(submitdate) AS subdate,
WEEKDAY(submitdate) AS day,
SUM(CASE WHEN WEEKDAY(DATE(submitdate)) = 0 THEN 1 END) AS PENDING,
SUM(CASE WHEN WEEKDAY(DATE(submitdate)) = 1 THEN 1 END) AS STARTED,
SUM(CASE WHEN WEEKDAY(DATE(submitdate)) = 2 THEN 1 END) AS INPROGRESS,
SUM(CASE WHEN WEEKDAY(DATE(submitdate)) = 3 THEN 1 END) AS CANCELLED,
SUM(CASE WHEN WEEKDAY(DATE(submitdate)) = 4 THEN 1 END) AS TERMINATED,
SUM(CASE WHEN WEEKDAY(DATE(submitdate)) = 5 THEN 1 END) AS UNKNOWN
FROM tb_sattus t1
WHERE employeenumber = 15
GROUP BY DATE(submitdate)
ORDER BY subdate
Note that your current query is not correct, because you are selecting string literals based on the status. Instead, in my query the various status types appear as column names, with the counts you want instead being selected.
Give this a try:
SELECT
`submitDate` as `date`,
DATE_FORMAT(`submitDate`,'%a') as `day`,
SUM(if(`statusvalue` = 0,1,0)) as `pending`,
SUM(if(`statusvalue` = 1,1,0)) as `started`,
SUM(if(`statusvalue` = 2,1,0)) as `inprogress`,
SUM(if(`statusvalue` = 3,1,0)) as `cancelled`,
SUM(if(`statusvalue` = 4,1,0)) as `terminated`,
SUM(if(`statusvalue` = 5,1,0)) as `unknown`,
SUM(if(NOT `statusvalue` IN (0,1,2,3,4,5),1,0)) as `invalid`,
COUNT(`statusvalue`) as `total`
FROM `tbstatus`
GROUP BY `submitDate`
ORDER BY `submitDate`;
Locked. There are disputes about this question’s content being resolved at this time. It is not currently accepting new answers or interactions.
I am new to SQL and would like to know how to approach writing a query for this question.
Lets say we have these fields:
date_created date_unsubscribed subscriberid
How to write a SQL query that lists, by month, how many people subscribed to the list, unsubscribed from the list, and how many net subscribers there were (new subscribers minus unsubscribers).
All in a single query...
Here's one option using conditional aggregation and union all:
select month(dt),
count(case when subscribe = 1 then 1 end) subscribecount,
count(case when subscribe = -1 then 1 end) unsubscribecountt,
sum(subscribe) overallcount
from (
select date_created as dt, 1 as subscribe
from yourtable
union all
select date_unsubscribed, -1
from yourtable
where date_unsubscribed is not null
) t
group by month(dt)
The subquery creates a list of dates with a flag for subscribe or unsubscribe. Then you can use count with case to determine the appropriate number of subscribers/unsubscribers.
SQL Fiddle Demo
You could write a sum(case) (a sum with conditions) to aggregate - assuming the date_created column is never null. For instance:
ORACLE:
SELECT
TO_CHAR(DATE_CREATED,'MM-YYYY') CREATE_MONTH
,SUM(CASE WHEN date_unsubscribed is not null then 1 else 0 end) unsubscribed
,SUM(CASE WHEN date_unsubscribed is null then 1 else 0 end) subscribed
,COUNT(SUBSCRIBER_ID)
FROM
--YOURTABLENAME
--WHERE
--WHATEVER OTHER CONDITIONS YOU HAVE APPLY
GROUP BY TO_CHAR(DATE_CREATED,'MM-YYYY')
MYSQL:
SELECT
DATE_FORMAT(DATE_CREATED,'%m-%Y') CREATE_MONTH
,SUM(CASE WHEN date_unsubscribed is not null then 1 else 0 end) unsubscribed
,SUM(CASE WHEN date_unsubscribed is null then 1 else 0 end) subscribed
,COUNT(SUBSCRIBER_ID)
FROM
--YOURTABLENAME
--WHERE
--WHATEVER OTHER CONDITIONS YOU HAVE APPLY
GROUP BY DATE_FORMAT(DATE_CREATED,'%m-%Y')
Oracle solution
Here is a query using the PIVOT operator, which was created exactly for this kind of work, and ROLLUP to get the net number. This is just for illustration; I assume the year is a user or application input (bind variable :year, set to 2015 for the output), and I show the summary for January through June.
with
test_data ( date_created, date_unsubscribed, subscriber_id ) as (
select date '2015-05-10', null , 330053448 from dual union all
select date '2015-04-28', null , 330053457 from dual union all
select date '2015-05-10', null , 330053466 from dual union all
select date '2015-04-28', null , 220053475 from dual union all
select date '2015-04-28', date '2015-05-10', 330053484 from dual
),
prep ( type, val, mth ) as (
select 'Subscribed' , 1, extract(month from date_created) from test_data
where extract(year from date_created) = :year
union all
select 'Unsubscribed', -1, extract(month from date_unsubscribed) from test_data
where extract(year from date_unsubscribed) = :year
)
select nvl(type, 'Net Subscr') as description,
nvl(sum(jan), 0) as jan, nvl(sum(feb), 0) as feb, nvl(sum(mar), 0) as mar,
nvl(sum(apr), 0) as apr, nvl(sum(may), 0) as may, nvl(sum(jun), 0) as jun
from prep
pivot (
sum(val)
for mth in (1 as jan, 2 as feb, 3 as mar, 4 as apr, 5 as may, 6 as jun)
)
group by rollup(type)
order by case type when 'Subscribed' then 1 when 'Unsubscribed' then 2 else 3 end
;
DESCRIPTION JAN FEB MAR APR MAY JUN
------------ ---------- ---------- ---------- ---------- ---------- ----------
Subscribed 0 0 0 3 2 0
Unsubscribed 0 0 0 0 -1 0
Net Subscr 0 0 0 3 1 0
3 rows selected.
I'm trying to create a GridView with ASP.NET connecting to a MySQL database. The data appears like below.
BusinessUnit OrderDate Canceled
UnitA 1/15/2013 N
UnitA 10/1/2013 N
UnitB 10/15/2013 N
UnitB 10/22/2013 N
UnitB 10/22/2013 N
Based on the records above, I'd like the result to appear like below
BusinessUnit TodaysOrders ThisMonthsOrders ThisYearsOrders
UnitA 0 1 2
UnitB 2 3 3
My current code is below. It's giving me error (something about DatabaseName.sum does not exist. Check the
Function Name Parsing and Resolution' section... )
Select
SUM (CASE WHEN (OrderDate)=DATE(NOW()) THEN 1 ELSE 0 END) AS TodaysOrders,
SUM (CASE WHEN YEAR(OrderDate) = YEAR(CURDATE()) AND MONTH(OrderDate) = MONTH(CURDATE()) THEN 1 ELSE 0 END) AS ThisMonthsOrders,
SUM (CASE WHEN YEAR(main_order_managers.creation_date) = YEAR(CURDATE()) THEN 1 ELSE 0 END) AS ThisYearsOrders
code continues
FROM OrderTable WHERE OrderTable.Canceled. <> 'Y';
Is Sum Case the best use here?
The error is caused by the space between function name and parenthesis
SUM (CASE WHEN ...
^^
Read more Function Name Parsing and Resolution
Try
SELECT BusinessUnit,
SUM(CASE WHEN OrderDate = CURDATE() THEN 1 ELSE 0 END) TodaysOrders,
SUM(CASE WHEN DATE_FORMAT(OrderDate, '%Y%m') = DATE_FORMAT(CURDATE(), '%Y%m') THEN 1 ELSE 0 END) ThisMonthsOrders,
SUM(CASE WHEN YEAR(OrderDate) = YEAR(CURDATE()) THEN 1 ELSE 0 END) ThisYearsOrders
FROM OrderTable
WHERE Canceled <> 'Y'
GROUP BY BusinessUnit
Here is SQLFiddle demo
I have a long sql query that calculates a few things about payments and shipments. In some cases the value is null. I think that's because there's being divided by 0.
Here's a small part of my query:
ROUND(sum(case when shipping_method = 'c' AND (paid_amount - shipping_costs) < 70 then 1 end) * 100 / sum(case when shipping_method = 'c' then 1 end),2) as co_less_70,
I think that when this part is 0: sum(case when shipping_method = 'colissimo' then 1 end),2) my query shows null. Is there any way to assign a default value for this co_less_70 column?
Yes. You can use the COALESCE() function:
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce
Returns the first non-NULL value in the list, or NULL if there are no non-NULL values.
In your code:
COALESCE(
ROUND(sum(case when shipping_method = 'c' AND (paid_amount - shipping_costs) < 70 then 1 end) * 100 / sum(case when shipping_method = 'c' then 1 end),2),
0
) AS co_less_70
IFNULL(
ROUND(sum(case when shipping_method = 'c' AND (paid_amount - shipping_costs) < 70 then 1 end) * 100 / sum(case when shipping_method = 'c' then 1 end),2)
,<default>) AS co_less_70,
You can set a default case, but anything except zero :-
sum(case when shipping_method = 'colissimo' then 1 else some_value end case),2)