inner join with pivot condition sql - mysql

I currently have the following sql query:
SELECT
name,
SUM( IF( MONTH(date) = 1, amount, 0) ) AS jan,
SUM( IF( MONTH(date) = 2, amount, 0) ) AS feb,
SUM( IF( MONTH(date) = 3, amount, 0) ) AS mar,
SUM( IF( MONTH(date) = 4, amount, 0) ) AS apr,
SUM( IF( MONTH(date) = 5, amount, 0) ) AS mei,
SUM( IF( MONTH(date) = 6, amount, 0) ) AS jun,
SUM( IF( MONTH(date) = 7, amount, 0) ) AS jul,
SUM( IF( MONTH(date) = 8, amount, 0) ) AS agu,
SUM( IF( MONTH(date) = 9, amount, 0) ) AS sep,
SUM( IF( MONTH(date) = 10, amount, 0) ) AS okt,
SUM( IF( MONTH(date) = 11, amount, 0) ) AS nov,
SUM( IF( MONTH(date) = 12, amount, 0) ) AS des,
SUM( amount ) AS total
FROM iuran_detail
WHERE (
date BETWEEN '$date_first' AND '$date_last'
) GROUP BY name;
I want modification with 2 tables sql, user table (along with group) and amount.
I want to combine the inner join or another way, to get the following result (e.g by group A):
thanks

Note: If joining tables it is best practice to prefix EVERY column reference with either the source table name OR by an alias given to the source table (I use the latter). "date" is a terrible column name as it is also used by SQL itself and can cause confusion, so below I have used the MySQL backticks to reference that column, in SQL-Server you could use [date] instead.
SELECT
u.name,
SUM( IF( MONTH(`date`) = 1, d.amount, 0) ) AS jan,
SUM( IF( MONTH(`date`) = 2, d.amount, 0) ) AS feb,
SUM( IF( MONTH(`date`) = 3, d.amount, 0) ) AS mar,
SUM( IF( MONTH(`date`) = 4, d.amount, 0) ) AS apr,
SUM( IF( MONTH(`date`) = 5, d.amount, 0) ) AS mei,
SUM( IF( MONTH(`date`) = 6, d.amount, 0) ) AS jun,
SUM( IF( MONTH(`date`) = 7, d.amount, 0) ) AS jul,
SUM( IF( MONTH(`date`) = 8, d.amount, 0) ) AS agu,
SUM( IF( MONTH(`date`) = 9, d.amount, 0) ) AS sep,
SUM( IF( MONTH(`date`) = 10, d.amount, 0) ) AS okt,
SUM( IF( MONTH(`date`) = 11, d.amount, 0) ) AS nov,
SUM( IF( MONTH(`date`) = 12, d.amount, 0) ) AS des,
SUM( d.amount ) AS total
FROM table_trx d
INNER JOIN table_user u on d.user_id = u.id
WHERE (
d.`date` BETWEEN '$`date`_first' AND '$`date`_last'
) GROUP BY u.name;
Personally I do not like using IF() as an alternative to the more standard CASE expression as it is more broadly supported in SQL databases.
SELECT
u.name,
SUM( case when MONTH(`date`) = 1 then d.amount else 0 end ) AS jan,
SUM( case when MONTH(`date`) = 2 then d.amount else 0 end ) AS feb,
SUM( case when MONTH(`date`) = 3 then d.amount else 0 end ) AS mar,
SUM( case when MONTH(`date`) = 4 then d.amount else 0 end ) AS apr,
SUM( case when MONTH(`date`) = 5 then d.amount else 0 end ) AS mei,
SUM( case when MONTH(`date`) = 6 then d.amount else 0 end ) AS jun,
SUM( case when MONTH(`date`) = 7 then d.amount else 0 end ) AS jul,
SUM( case when MONTH(`date`) = 8 then d.amount else 0 end ) AS agu,
SUM( case when MONTH(`date`) = 9 then d.amount else 0 end ) AS sep,
SUM( case when MONTH(`date`) = 10 then d.amount else 0 end ) AS okt,
SUM( case when MONTH(`date`) = 11 then d.amount else 0 end ) AS nov,
SUM( case when MONTH(`date`) = 12 then d.amount else 0 end ) AS des,
SUM( d.amount ) AS total
FROM table_trx d
INNER JOIN table_user u on d.user_id = u.id
WHERE (
d.`date` BETWEEN '$`date`_first' AND '$`date`_last'
) GROUP BY u.name;

Related

Explain me ways to understand this complex query

Can anyone help me to understand this big sql query. How do I break it down in small chunks to understand it ?
select t.Instrument as Instrument ,ClearingId as ClearingId,
ISNULL( PrevQty ,0) AS PrevQty,SettlePrice,
ISNULL(TodayBuyQty,0) as TodayBuyQty,
ISNULL( TodaySellQty ,0) AS TodaySellQty,
ISNULL(PrevQty +TodayBuyQty-TodaySellQty,0) as NetQty,
TodayBuyPrice, TodaySellPrice,LTP,PnL,Token
from
(
select Instrument,w.ClearingId as ClearingId,
ISNULL( PrevQty ,0) AS PrevQty,ISNULL(TodayBuyQty,0) as TodayBuyQty,
ISNULL( TodaySellQty ,0) AS TodaySellQty,
TodayAvgBuyPrice as TodayBuyPrice,TodayAvgSellPrice as TodaySellPrice,
LTP,PnL,w.Token
from
(
select Symbol as Instrument, ClearingId,
ISNULL(TodayBuyQty,0) as TodayBuyQty,
TodayAvgBuyPrice,
ISNULL( -TodaySellQty ,0) AS TodaySellQty,
TodayAvgSellPrice, NULL as LTP ,NULL as PnL ,
w.Token as Token
from
(
select Token, sum(Qty) as NetPositionQty, ClearingId,
sum(CASE WHEN Qty < 0 THEN Qty ELSE 0 END) as TodaySellQty,
sum(CASE WHEN Qty > 0 THEN Qty ELSE 0 END) as TodayBuyQty,
sum(CASE WHEN Qty < 0 THEN Qty * Price ELSE 0 END)
/
NULLIF(sum(CASE WHEN Qty < 0 THEN Qty ELSE 0 END), 0) as TodayAvgSellPrice,
sum(CASE WHEN Qty > 0 THEN Qty * Price ELSE 0 END)
/
NULLIF(sum(CASE WHEN Qty > 0 THEN Qty ELSE 0 END), 0) as TodayAvgBuyPrice
from
(
select m.Token,
(CASE WHEN ClearingId = 'SATP' THEN 'STRAITS' ELSE CASE WHEN ClearingId = 'BATP' THEN 'BPI' ELSE 'UOB' END END ) as ClearingId ,
Price/CAST(Multiplier AS float ) as Price,Qty
from
(
select Token , Exchange as ClearingId ,
LastTradePrice as Price ,
CASE WHEN Side = 'S' THEN -LastTradeQuantity ELSE LastTradeQuantity END as Qty
from Strategy_Orders
where ExchangeStatus in (9,10) )m
JOIN TokenMap t ON ( m.Token = t.Token)
UNION ALL
select m.Token, (CASE WHEN ClearingId = 'SATP' THEN 'STRAITS' ELSE CASE WHEN ClearingId = 'BATP' THEN 'BPI' ELSE 'UOB' END END ) as ClearingId ,
Price/CAST(Multiplier AS float ) as Price,
Qty
from
(
select Token , Exchange as ClearingId ,
LastTradePrice as Price ,
CASE WHEN Side = 'S' THEN -LastTradeQuantity ELSE LastTradeQuantity END as Qty
from Manual_Orders
where ExchangeStatus in (9,10) )m
JOIN TokenMap t ON ( m.Token = t.Token)
UNION ALL
select Token , ClearingId , TodayBuyPrice ,
TodayBuyQty as Qty
from EOD_Holdings
where CurrentDate =
( select top 1 CurrentDAte from EOD_Holdings
order by CurrentDAte desc
)
UNION ALL
select Token , ClearingId , TodaySellPrice ,
TodaySellQty as Qty
from EOD_Holdings
where CurrentDate = (
select top 1 CurrentDAte from EOD_Holdings
order by CurrentDAte desc
)
) x
group by Token,ClearingId) w
JOIN(select Token, Symbol from TokenMAp ) h on w.Token = h.Token
) w
FULL OUTER JOIN(
select Token, PrevQty , ClearingId
from EOD_Holdings
where CurrentDate = ( select top 1 CurrentDAte from EOD_Holdings order by CurrentDAte desc
)
) h
on w.Token = h.Token and w.ClearingId = h.ClearingId
)t
JOIN (
select * from LatestSettlePrices
) sp
on t.Instrument = sp.Instrument
You can break the query into chunks by looking at each subquery ("select ..." ) separately and running them to see the results. You need to start with the innermost queries that do not have other select statements in the "from" or "where" clause.
Also note that this query does not seem to be a clear, neither an optimal solution.
You would want to avoid using full outer joins and union all statements for the best performance.

Adapting two queries

Hello again community.
I recently received help with the solution to a problem that consisted of List grouped data by month including months in which there are no results
Now I have the same scenario but with the difference that there is a condition to evaluate. I need to adapt this query
select
date_format(a.date_created, '%b') month,
month(a.date_created) pivot,
sum(case when a.state = 'created' then 1 else 0 end) created,
sum(case when a.state = 'notified' then 1 else 0 end) notified,
sum(case when a.state = 'confirmed' then 1 else 0 end) confirmed,
sum(case when a.state = 'approved' then 1 else 0 end) approved,
sum(case when a.state = 'authorized' then 1 else 0 end) authorized,
sum(case when a.state = 'attended' then 1 else 0 end) attended,
sum(case when a.state = 'canceled' then 1 else 0 end) canceled,
count(a.id) as total
from
activities a
inner join
employees e on a.employee_id = e.id
where
e.id = 8
group by 1, 2 order by pivot desc;
To this query
select
s.name month,
s.m pivot,
sum(case when a.state = 'created' then 1 else 0 end) created,
sum(case when a.state = 'notified' then 1 else 0 end) notified,
sum(case when a.state = 'confirmed' then 1 else 0 end) confirmed,
sum(case when a.state = 'approved' then 1 else 0 end) approved,
sum(case when a.state = 'authorized' then 1 else 0 end) authorized,
sum(case when a.state = 'attended' then 1 else 0 end) attended,
sum(case when a.state = 'canceled' then 1 else 0 end) canceled,
count(a.id) as total
from (
SELECT 1 m, 'Jan' AS name
UNION SELECT 2, 'Feb'
UNION SELECT 3, 'Mar'
UNION SELECT 4, 'Apr'
UNION SELECT 5, 'May'
UNION SELECT 6, 'Jun'
UNION SELECT 7, 'Jul'
UNION SELECT 8, 'Aug'
UNION SELECT 9, 'Sep'
UNION SELECT 10, 'Oct'
UNION SELECT 11, 'Nov'
UNION SELECT 12, 'Dec'
) s
LEFT JOIN activities a
ON s.m = month(date_created)
group by 1, 2 order by pivot desc;
I do not know how in the context of the solution that worked in the previous question add the condition
I have tested the following but the months in which there are no results are not listed
select
s.name month,
s.m pivot,
sum(case when a.state = 'created' then 1 else 0 end) created,
sum(case when a.state = 'notified' then 1 else 0 end) notified,
sum(case when a.state = 'confirmed' then 1 else 0 end) confirmed,
sum(case when a.state = 'approved' then 1 else 0 end) approved,
sum(case when a.state = 'authorized' then 1 else 0 end) authorized,
sum(case when a.state = 'attended' then 1 else 0 end) attended,
sum(case when a.state = 'canceled' then 1 else 0 end) canceled,
count(a.id) as total
from (
SELECT 1 m, 'Jan' AS name
UNION SELECT 2, 'Feb'
UNION SELECT 3, 'Mar'
UNION SELECT 4, 'Apr'
UNION SELECT 5, 'May'
UNION SELECT 6, 'Jun'
UNION SELECT 7, 'Jul'
UNION SELECT 8, 'Aug'
UNION SELECT 9, 'Sep'
UNION SELECT 10, 'Oct'
UNION SELECT 11, 'Nov'
UNION SELECT 12, 'Dec'
) s
LEFT JOIN activities a
ON s.m = month(date_created)
inner join employees e on a.employee_id = e.id
group by 1, 2 order by pivot desc;
I share the following sqlfiddle that includes the relationship between employee and activity
I am expecting for the user with id 2 the results should be as follows
Again, thank you very much.
You just had the joins muddled. For the join between activities and employees to be considered as INNER join it has to be enclosed in brackets. Let's know whether it works!
Here is the solution
select
s.name month,
s.m pivot,
sum(case when a.state = 'created' then 1 else 0 end) created,
sum(case when a.state = 'notified' then 1 else 0 end) notified,
sum(case when a.state = 'confirmed' then 1 else 0 end) confirmed,
sum(case when a.state = 'approved' then 1 else 0 end) approved,
sum(case when a.state = 'authorized' then 1 else 0 end) authorized,
sum(case when a.state = 'attended' then 1 else 0 end) attended,
sum(case when a.state = 'canceled' then 1 else 0 end) canceled,
count(a.id) as total
from (
SELECT 1 m, 'Jan' AS name
UNION SELECT 2, 'Feb'
UNION SELECT 3, 'Mar'
UNION SELECT 4, 'Apr'
UNION SELECT 5, 'May'
UNION SELECT 6, 'Jun'
UNION SELECT 7, 'Jul'
UNION SELECT 8, 'Aug'
UNION SELECT 9, 'Sep'
UNION SELECT 10, 'Oct'
UNION SELECT 11, 'Nov'
UNION SELECT 12, 'Dec'
) s
LEFT JOIN ( activities a INNER JOIN employees e
ON a.employee_id = e.id AND e.id = 2)
ON (s.m = month(a.date_created))
group by 1, 2 order by pivot desc;
I think this version does what you want:
select s.name as month, s.m as pivot,
sum(case when a.state = 'created' then 1 else 0 end) created,
sum(case when a.state = 'notified' then 1 else 0 end) notified,
sum(case when a.state = 'confirmed' then 1 else 0 end) confirmed,
sum(case when a.state = 'approved' then 1 else 0 end) approved,
sum(case when a.state = 'authorized' then 1 else 0 end) authorized,
sum(case when a.state = 'attended' then 1 else 0 end) attended,
sum(case when a.state = 'canceled' then 1 else 0 end) canceled,
count(a.id) as total
from (SELECT 1 m, 'Jan' AS name UNION ALL
SELECT 2, 'Feb' UNION ALL
SELECT 3, 'Mar' UNION ALL
SELECT 4, 'Apr' UNION ALL
SELECT 5, 'May' UNION ALL
SELECT 6, 'Jun' UNION ALL
SELECT 7, 'Jul' UNION ALL
SELECT 8, 'Aug' UNION ALL
SELECT 9, 'Sep' UNION ALL
SELECT 10, 'Oct' UNION ALL
SELECT 11, 'Nov' UNION ALL
SELECT 12, 'Dec'
) s LEFT JOIN activities a
ON s.m = month(date_created) left join
employees e
on a.employee_id = e.id AND e.id = 2
group by 1, 2
order by pivot desc;
Here is the SQL Fiddle.
The major change is moving the condition on e.id to the ON clause and changing the second join to a LEFT JOIN. In addition, I changed the UNION to UNION ALL, to eliminate the overhead of removing duplicates.

How can I make this SQL query more elegant?

This is my MySQL query for getting count values...
SELECT 1 AS id,
'2016' AS Year,
MAX( IF( Month = '01', Count, 0 ) ) AS 'VAL01',
MAX( IF( Month = '02', Count, 0 ) ) AS 'VAL02',
MAX( IF( Month = '03', Count, 0 ) ) AS 'VAL03',
MAX( IF( Month = '04', Count, 0 ) ) AS 'VAL04',
MAX( IF( Month = '05', Count, 0 ) ) AS 'VAL05',
MAX( IF( Month = '06', Count, 0 ) ) AS 'VAL06',
MAX( IF( Month = '07', Count, 0 ) ) AS 'VAL07',
MAX( IF( Month = '08', Count, 0 ) ) AS 'VAL08',
MAX( IF( Month = '09', Count, 0 ) ) AS 'VAL09',
MAX( IF( Month = '10', Count, 0 ) ) AS 'VAL10',
MAX( IF( Month = '11', Count, 0 ) ) AS 'VAL11',
MAX( IF( Month = '12', Count, 0 ) ) AS 'VAL12',
SUM( Count ) AS Total
FROM ( SELECT DATE_FORMAT( created_at, '%m' ) AS Month,
COUNT( 1 ) AS Count
FROM reservations
WHERE DATE_FORMAT( created_at, '%Y' ) = '2016'
GROUP BY DATE_FORMAT( created_at, '%m' )
) AS T1
UNION
SELECT 2 AS id,
'2017' AS Year,
MAX( IF( Month = '01', Count, 0 ) ) AS 'VAL01',
MAX( IF( Month = '02', Count, 0 ) ) AS 'VAL02',
MAX( IF( Month = '03', Count, 0 ) ) AS 'VAL03',
MAX( IF( Month = '04', Count, 0 ) ) AS 'VAL04',
MAX( IF( Month = '05', Count, 0 ) ) AS 'VAL05',
MAX( IF( Month = '06', Count, 0 ) ) AS 'VAL06',
MAX( IF( Month = '07', Count, 0 ) ) AS 'VAL07',
MAX( IF( Month = '08', Count, 0 ) ) AS 'VAL08',
MAX( IF( Month = '09', Count, 0 ) ) AS 'VAL09',
MAX( IF( Month = '10', Count, 0 ) ) AS 'VAL10',
MAX( IF( Month = '11', Count, 0 ) ) AS 'VAL11',
MAX( IF( Month = '12', Count, 0 ) ) AS 'VAL12',
SUM( Count ) AS Total
FROM ( SELECT DATE_FORMAT( created_at, '%m' ) AS Month,
COUNT( 1 ) AS Count
FROM reservations
WHERE DATE_FORMAT( created_at, '%Y' ) = '2017'
GROUP BY DATE_FORMAT( created_at, '%m' )
) AS T2
It returns (for example)...
+----+------+-------+-------+-------+-------+-------+-------+-----+-------+-------+
| id | Year | VAL01 | VAL02 | VAL03 | VAL04 | VAL05 | VAL06 | ... | VAL12 | Total |
+----+------+-------+-------+-------+-------+-------+-------+-----+-------+-------+
| 1 | 2016 | 0 | 0 | 150 | 190 | 200 | 220 | ... | 160 | 1242 |
+----+------+-------+-------+-------+-------+-------+-------+-----+-------+-------+
| 2 | 2017 | 300 | 300 | 600 | 600 | 700 | 0 | ... | 0 | 2500 |
+----+------+-------+-------+-------+-------+-------+-------+-----+-------+-------+
My query has many problems. It can't use the year 2018 and it should use UNION again and again.
How can I make my SQL query more beautiful?
Try this
select
date_format(created_at,'%Y') as Year,
sum(case when date_format(created_at,'%m')='01' then 1 else 0 end) as val01,
sum(case when date_format(created_at,'%m')='02' then 1 else 0 end) as val02,
sum(case when date_format(created_at,'%m')='03' then 1 else 0 end) as val03,
sum(case when date_format(created_at,'%m')='04' then 1 else 0 end) as val04,
sum(case when date_format(created_at,'%m')='05' then 1 else 0 end) as val05,
sum(case when date_format(created_at,'%m')='06' then 1 else 0 end) as val06,
sum(case when date_format(created_at,'%m')='07' then 1 else 0 end) as val07,
sum(case when date_format(created_at,'%m')='08' then 1 else 0 end) as val08,
sum(case when date_format(created_at,'%m')='09' then 1 else 0 end) as val09,
sum(case when date_format(created_at,'%m')='10' then 1 else 0 end) as val10,
sum(case when date_format(created_at,'%m')='11' then 1 else 0 end) as val11,
sum(case when date_format(created_at,'%m')='12' then 1 else 0 end) as val12,
count(*) as total
from reservations
group by date_format(created_at,'%Y')
You can try with below query
SELECT YEAR,SUM(VAL01) VAL02,SUM(VAL02) VAL02,SUM(VAL03) VAL3
FROM
(
SELECT date_format(created_at,'%Y') YEAR,
CASE WHEN date_format(created_at,'%m')=1 THEN 1 ELSE 0 END AS VAL01,
CASE WHEN date_format(created_at,'%m')=2 THEN 1 ELSE 0 END AS VAL02,
CASE WHEN date_format(created_at,'%m')=3 THEN 1 ELSE 0 END AS VAL03
FROM reservations
)t
GROUP BY YEAR
Hope this will helps.
If this had been Oracle, you could have used Function based index on column Created_at and using the same function (EXTRACT in this case) in your query:
CREATE INDEX IDX1 ON RESERVATIONS (EXTRACT(YEAR FROM CREATED_AT))
Since, this is MySQL, try using this as alternative. Make sure after creating the index, it is getting used by verifying the Query plan.
You could try this query
SELECT id,
Year,
SUM(CASE WHEN Month='01' THEN MonthCount ELSE 0 END) AS 'VAL01',
SUM(CASE WHEN Month='02' THEN MonthCount ELSE 0 END) AS 'VAL02',
SUM(CASE WHEN Month='03' THEN MonthCount ELSE 0 END) AS 'VAL03',
SUM(CASE WHEN Month='04' THEN MonthCount ELSE 0 END) AS 'VAL04',
SUM(CASE WHEN Month='05' THEN MonthCount ELSE 0 END) AS 'VAL05',
SUM(CASE WHEN Month='06' THEN MonthCount ELSE 0 END) AS 'VAL06',
SUM(CASE WHEN Month='07' THEN MonthCount ELSE 0 END) AS 'VAL07',
SUM(CASE WHEN Month='08' THEN MonthCount ELSE 0 END) AS 'VAL08',
SUM(CASE WHEN Month='09' THEN MonthCount ELSE 0 END) AS 'VAL09',
SUM(CASE WHEN Month='10' THEN MonthCount ELSE 0 END) AS 'VAL10',
SUM(CASE WHEN Month='11' THEN MonthCount ELSE 0 END) AS 'VAL11',
SUM(CASE WHEN Month='12' THEN MonthCount ELSE 0 END) AS 'VAL12',
SUM(MonthCount) AS Total
FROM (
SELECT
CASE
WHEN Date_format(created_at, '%Y') = '2016' THEN 1
WHEN Date_format(created_at, '%Y') = '2017' THEN 2
WHEN Date_format(created_at, '%Y') = '2018' THEN 3
END AS id,
Date_format(created_at, '%Y') AS Year,
Date_format(created_at, '%m') AS Month,
COUNT(1) AS MonthCount
FROM reservations
WHERE Date_format(created_at, '%Y') IN ('2016', '2017', '2018')
GROUP BY Date_format(created_at, '%Y-%m')) AS ByMonth
GROUP BY id, Year

Case in where condition to calculate individual totals

select
Count(*)
from gl
join TRVMAINDATA msit
on gl.TRANSACTIONID = msit.CHARGETRANSACTIONID
where gl.CREATEDDATETIME >= DATEADD(MONTH,-2,getdate()) AND
datediff(DAY,gl.BUSINESSPROCESSDATE,gl.CREATEDDATETIME)>=4 AND
gl.MARKETCODE In('535','532','056','050','039','036','034','033','030','029','027','023','022','021','018','015','012','011','010','009','007','006','005','002','001' ) and DATEADD(MONTH,DATEDIFF(MONTH,0,gl.CREATEDDATETIME),0) = '2/1/2017 12:00:00 AM'
The above code gives the total for market code mentioned.
But i also want the market code for other code which doesn't belog here. for example
select
Count(*)
from gl
join TRVMAINDATA msit
on gl.TRANSACTIONID = msit.CHARGETRANSACTIONID
where gl.CREATEDDATETIME >= DATEADD(MONTH,-6,getdate()) AND
datediff(DAY,gl.BUSINESSPROCESSDATE,gl.CREATEDDATETIME)>=0
and
DATEADD(MONTH,DATEDIFF(MONTH,0,gl.CREATEDDATETIME),0) = '2/1/2017 12:00:00 AM'
AND
(case
when gl.MARKETCODE In('535','532','056','050','039','036','034','033','030','029','027','023','022','021','018','015','012','011','010','009','007','006','005','002','001') then 'Proprietary'
when gl.MARKETCODE='037' then 'US'
else 'partner'
end )
Is it possible to calculate totals of other market codes in one sql query or do i have to calculate individually?
I think you would like to do count with case when in select statement like this:
SELECT COUNT(CASE
WHEN gl.marketcode IN ( '535', '532', '056', '050',
'039', '036', '034', '033',
'030', '029', '027', '023',
'022', '021', '018', '015',
'012', '011', '010', '009',
'007', '006', '005', '002', '001' ) THEN 1
ELSE NULL
END) AS `Proprietary`,
COUNT(CASE
WHEN gl.marketcode = '037' THEN 1
ELSE NULL
END) AS `US`,
COUNT(CASE
WHEN gl.marketcode NOT IN ( '535', '532', '056', '050',
'039', '036', '034', '033',
'030', '029', '027', '023',
'022', '021', '018', '015',
'012', '011', '010', '009',
'007', '006', '005', '002',
'001', '037' ) THEN 1
ELSE NULL
END) AS `partner`
FROM gl
JOIN trvmaindata msit
ON gl.transactionid = msit.chargetransactionid
WHERE gl.createddatetime >= DATEADD(month, -2, GETDATE())
AND DATEDIFF(day, gl.businessprocessdate, gl.createddatetime) >= 4
AND DATEADD(month, DATEDIFF(month, 0, gl.createddatetime), 0) = '2/1/2017 12:00:00 AM'

SQL query - How to exclude WHERE for specific field

See the SQL query below, it work fine. It calculate the number of Yes, NOT, Other and the number of matching mobile number [Sales field] (D.MobileNo = S.mobile)
SELECT D.Username,
SUM(CASE WHEN D.type = 'Yes' THEN 1 ELSE 0 END) as Yes,
SUM(CASE WHEN D.type = 'Not' THEN 1 ELSE 0 END) as Not,
SUM(CASE WHEN D.type = '' THEN 1 ELSE 0 END) as Other,
SUM(CASE WHEN S.mobile IS NULL THEN 0 ELSE 1 END) as Sales,
COUNT(*) as TOTAL
FROM dairy as D
LEFT JOIN (SELECT DISTINCT mobile FROM sales) as S on D.MobileNo = S.mobile
WHERE source = 'Network'
AND UNIX_TIMESTAMP(CheckDate) >= 1309474800
AND UNIX_TIMESTAMP(CheckDate) <= 1311894000
GROUP BY D.Username
ORDER BY TOTAL DESC
I want to exclude WHERE for the Sales field - it should not be part from CheckDate. Meaning it should check any record in the dairy table without CheckDate for the Sales field.
How can that be done?
If you really want those results in only one query, this might do the trick.
SELECT D.Username,
SUM(CASE WHEN D.type = 'Yes' AND UNIX_TIMESTAMP(CheckDate) >= 1309474800 AND UNIX_TIMESTAMP(CheckDate) <= 1311894000 THEN 1 ELSE 0 END) as Yes,
SUM(CASE WHEN D.type = 'Not' AND UNIX_TIMESTAMP(CheckDate) >= 1309474800 AND UNIX_TIMESTAMP(CheckDate) <= 1311894000 THEN 1 ELSE 0 END) as Not,
SUM(CASE WHEN D.type = '' AND UNIX_TIMESTAMP(CheckDate) >= 1309474800 AND UNIX_TIMESTAMP(CheckDate) <= 1311894000 THEN 1 ELSE 0 END) as Other,
SUM(CASE WHEN S.mobile IS NULL THEN 0 ELSE 1 END) as Sales,
COUNT(*) as TOTAL,
SUM(CASE WHEN UNIX_TIMESTAMP(CheckDate) >= 1309474800 AND UNIX_TIMESTAMP(CheckDate) <= 1311894000 THEN 1 ELSE 0 END) AS TOTALINCHECKDATE
FROM dairy as D
LEFT JOIN (SELECT DISTINCT mobile FROM sales) as S on D.MobileNo = S.mobile
WHERE source = 'Network'
GROUP BY D.Username
ORDER BY TOTAL DESC
Note that "TOTAL" will count all rows (including those who where not within your CheckDate range), TOTALINCHECKDATE return the same value as in your previous query.
Obviously, this can still be optimized.
Assuming username exists also in SALES table
SELECT Username,SUM(Yes) As Yes, SUM(`Not`) As `Not`
, SUM(Other) As Other, SUM(sales) Sales, SUM(total)
FROM (
-- get diary data
SELECT username,mobileNo As mobile,
CASE WHEN D.type = 'Yes' THEN 1 ELSE 0 END as Yes,
CASE WHEN D.type = 'Not' THEN 1 ELSE 0 END as `Not`,
CASE WHEN D.type = '' THEN 1 ELSE 0 END as Other,
0 As sales, 1 as total
FROM dairy as D
WHERE source = 'Network'
AND UNIX_TIMESTAMP(CheckDate) >= 1309474800
AND UNIX_TIMESTAMP(CheckDate) <= 1311894000
UNION ALL
-- get all sales
SELECT DISTINCT username,mobile, 0 as Yes, 0 as `Not`, 0 As Other, 1 As sales, 0 As total
FROM sales
WHERE UNIX_TIMESTAMP(CheckDate) >= 1309474800
AND UNIX_TIMESTAMP(CheckDate) <= 1311894000
) AS a
GROUP BY Username
Also try your original query with date addition
SELECT D.Username,
SUM(CASE WHEN D.type = 'Yes' THEN 1 ELSE 0 END) as Yes,
SUM(CASE WHEN D.type = 'Not' THEN 1 ELSE 0 END) as Not,
SUM(CASE WHEN D.type = '' THEN 1 ELSE 0 END) as Other,
SUM(CASE WHEN S.mobile IS NULL THEN 0 ELSE 1 END) as Sales,
COUNT(*) as TOTAL
FROM dairy as D
LEFT JOIN (SELECT DISTINCT mobile FROM sales WHERE UNIX_TIMESTAMP(CheckDate) >= 1309474800 AND UNIX_TIMESTAMP(CheckDate) <= 1311894000 ) as S on D.MobileNo = S.mobile
WHERE source = 'Network'
AND UNIX_TIMESTAMP(CheckDate) >= 1309474800
AND UNIX_TIMESTAMP(CheckDate) <= 1311894000
GROUP BY D.Username
ORDER BY TOTAL DESC