trying to get the single exp payment - mysql

I have a query like this
SELECT member_Id ,
PERIOD_DIFF(
DATE_FORMAT(now(),'%Y%m'),
DATE_FORMAT(memberToMship_StartDate,'%Y%m')
) +
(
DAY(memberToMship_StartDate) < memberToMship_DueDay
) +
(
DAY(now()) > memberToMship_DueDay
) - 1
AS ExpPayments
FROM membertomships
it was giving all exp payments for all members that was fine, can i get the single exp payment for single member.....
Do i need add any join or any where condition ..

If you know the member_Id you could just add a WHERE clause :
SELECT member_Id ,
PERIOD_DIFF(
DATE_FORMAT(now(),'%Y%m'),
DATE_FORMAT(memberToMship_StartDate,'%Y%m')
) +
(
DAY(memberToMship_StartDate) < memberToMship_DueDay
) +
(
DAY(now()) > memberToMship_DueDay
) - 1
AS ExpPayments
FROM membertomships
WHERE member_Id = 213

add where clause in the end of the query
where member_Id = {enter the id}

Related

Count Total from Multiple Tables

I have list table that basically contains same field on each part.
- p_ticket1_m_site_data | - p_ticket1_ticket | - p_ticket1_last_row
- p_ticket2_m_site_data | - p_ticket2_ticket | - p_ticket2_last_row
- p_ticket3_m_site_data | - p_ticket3_ticket | - p_ticket3_last_row
I can do a count on each table individually:
SELECT COUNT( * ) AS tot_sites, IFNULL( COUNT(
CASE WHEN p_ticket1_m_site_data.m_date_target = DATE( NOW( ) )
THEN 1
ELSE NULL
END ),0) AS todays_target, IFNULL( COUNT(
CASE WHEN (
p_ticket1_m_site_data.m_date_target = DATE( NOW( ) )
AND p_ticket1_ticket.t_status =9 )
THEN 1
ELSE NULL
END ),0
) AS todays_achieve, IFNULL( COUNT(
CASE WHEN p_ticket1_ticket.t_status =9
THEN 1
ELSE NULL
END ),0 ) AS tot_in
FROM p_ticket1_m_site_data
LEFT JOIN p_ticket1_last_row ON p_ticket1_last_row.t_m_id = p_ticket1_m_site_data.m_id
AND p_ticket1_last_row.t_req_type = '04_int_finish_ack'
LEFT JOIN p_ticket1_ticket ON p_ticket1_ticket.t_id = p_ticket1_last_row.t_id
WHERE p_ticket1_m_site_data.m_status =1
What should i do if i want to count all total sites from ticket1, ticket2, ticket3 ?
Please help me guys, thanks . . .
Example use UNION ALL:
I just using UNION ALL in my code above for ticket1 and ticket2, but its not what i want.
My expectation output is count all the ticket tables, so the view is tot_sites (from all ticket), todays_target(from all ticket), todays_achieve(from all ticket), and tot_in(from all ticket)
If you are sure that your tables have the same columns, you should use UNION ALL with CTE
WITH CTE AS (
SELECT *
FROM p_ticket1_m_site_data
UNION ALL
SELECT *
FROM p_ticket2_m_site_data
UNION ALL
...
)
SELECT COUNT(*), ...
FROM CTE
WHERE CTE.m_status = 1
CTE
UNION ALL
You can union the three sets of tables in a sub query and then do your counts in the main query , something like this in principal
SELECT COUNT( * ) AS tot_sites, IFNULL( COUNT(
CASE WHEN m_date_target = DATE( NOW( ) )
THEN 1
ELSE NULL
END ),0) AS todays_target, IFNULL( COUNT(
CASE WHEN (m_date_target = DATE( NOW( ) )
AND t_status =9 )
THEN 1
ELSE NULL
END ),0
) AS todays_achieve, IFNULL( COUNT(
CASE WHEN t_status =9
THEN 1
ELSE NULL
END ),0 ) AS tot_in
from
(
select *
FROM p_ticket1_m_site_data
LEFT JOIN p_ticket1_last_row ON p_ticket1_last_row.t_m_id = p_ticket1_m_site_data.m_id
AND p_ticket1_last_row.t_req_type = '04_int_finish_ack'
LEFT JOIN p_ticket1_ticket ON p_ticket1_ticket.t_id = p_ticket1_last_row.t_id
WHERE p_ticket1_m_site_data.m_status =1
union all
select *
frOM p_ticket2_m_site_data
LEFT JOIN p_ticket2_last_row ON p_ticket2_last_row.t_m_id = p_ticket2_m_site_data.m_id
AND p_ticket2_last_row.t_req_type = '04_int_finish_ack'
LEFT JOIN p_ticket2_ticket ON p_ticket2_ticket.t_id = p_ticket2_last_row.t_id
WHERE p_ticket2_m_site_data.m_status =1
union all
select *
fROM p_ticket3_m_site_data
LEFT JOIN p_ticket3_last_row ON p_ticket3_last_row.t_m_id = p_ticket3_m_site_data.m_id
AND p_ticket3_last_row.t_req_type = '04_int_finish_ack'
LEFT JOIN p_ticket3_ticket ON p_ticket3_ticket.t_id = p_ticket3_last_row.t_id
WHERE p_ticket3_m_site_data.m_status =1
) j;
Which could be tidied up. If this doesn't work for you please add sample data and expected output for your 3 tables as text to the question and I will review.

Rolling 12 month with Multiple columns (or dimension) in SQL Server 2008?

Let suppose i have these fields in my table Year, Month, Customer,Market,Product,Production Place, Category and Sales(decimal). Now I want an addition column Rolling 12 Sales which calculates sum of sales for current month + past 11 month.
rolling 12 sales (feb 2014)= sales (march 2013)+ sales (april 2013)+..........+sale (Feb 2014)
We have already achieved it using Co-related Sub query with AND condition for all the dimension, but that doesn't provides right out put!
Co-related sub=query works when i have only 4 colum like year, month , customer and sales
Please help!
Regards
Sushant
I'm going to assume that if your table's columns are
Year, Month, Customer,Market,Product,Production Place, Category and Sales(decimal)
... you want your Rolling 12 Sales column to be only the last 12 months' sales for that customer, market, product, production place, and category, rather than summarized to some higher level.
You don't say whether any of these columns can be Null, but I'm going to assume they can't, for simplicity.
I would expect this to work (given the conditions I mention above):
Select Year
, Month
, Customer
, Market
, Product
, [Production Place]
, Category
, Sales
, [Rolling 12 Month] =
(Select SUM(t2.Sales)
From Table1 t2
Where t1.Customer = t2.Customer
and t1.Market = t2.Market
and t1.Product = t2.Product
and T1.[Production Place] = t2.[Production Place]
and t1.Category = t2.Category
and (
(t2.Year = t1.Year and t2.Month <= t1.Month)
OR (t2.Year = t1.Year - 1 and t2.Month > t1.Month)
)
)
From Table1 t1
If any of those columns in the subquery's WHERE clause are nullable, change their format to this:
Where ((t1.Market = t2.Market) or (t1.Market IS NULL and t2.Market IS NULL))
If this doesn't work, please explain what error message or incorrect data you get. Thanks.
ETA: You asked whether this could be made to work in a stored procedure. I don't see why it couldn't. You didn't say what the parameters of the stored procedure needed to be (Customer? Current Year and Month?) so the version below has no parameters and returns data for all products and customers that had activity for the last twelve months.
Create dbo.Procedure1()
AS
Begin
declare #CurrentMonth int
, #CurrentYear int
-- If you want to parameterize this, you could make #CurrentMonth and #CurrentYear parameters
-- and skip this.
set #currentMonth = DatePart(MM, GetDate())
set #CurrentYear = DatePart(YYYY,GetDate())
;
with SalesFor12Months
as (
select Year
, Month
, Customer
, Market
, Product
, [Production Place]
, Category
, Sales
from Table1 t1
where (#CurrentYear = T1.Year and #CurrentMonth >= t1.Month)
OR (#CurrentYear - 1 = t1.Year and #CurrentMonth < t1.Month)
)
, SalesForCurrentMonth
as (
select *
from Table1
where Month = #CurrentMonth
and Year = #CurrentYear
)
, AllCustomers
as (
select distinct
Customer
, Market
, Product
, [Production Place]
, Category
from SalesFor12Months
)
select Month = #CurrentMonth
, Year = #CurrentYear
, ac.Customer
, ac.Market
, ac.Product
, ac.[Production Place]
, ac.Category
, Sales = COALESCE(curSales.Sales,0)
, [Rolling 12 Month] = COALESCE(
(Select SUM(t2.Sales)
From SalesFor12Months t2
Where ac.Customer = t2.Customer
and ac.Market = t2.Market
and ac.Product = t2.Product
and ac.[Production Place] = t2.[Production Place]
and ac.Category = t2.Category
)
,0)
from AllCustomers ac
left join SalesForCurrentMonth curSales
on ac.Customer = curSales.Customer
and ac.Market = curSales.Market
and ac.Product = curSales.Product
and ac.[Production Place] = curSales.[Production Place]
and ac.Category = curSales.Category
End
Hope that helps. I did that without having test data so I apologize if there are typos or other errors.
Join SELECT
'PMD' as RecType,
PMID as RecID,
CustomerID,
PMMonth as Month,
PMYear as Year,
Quantity as Rolling12Packs,
Size * Quantity / 1000 AS Rolling12Litres,
(PMDelSpl.Method) as Method,
(PMDelSpl.Size) as Size,
(PMDelSpl.Shape) as Shape,
(PMDelSpl.System) as System,
(PMDelSpl.Type) as Type,
(PMDelSpl.Category) as Category,
(PMDelSpl.SubCat) as SubCat,
(PMDelSpl.Place) as Place,
PMDelSpl.Group,
PMDelSpl.Distribution,
convert( datetime, str( PMYear ) + '/' + STR( PMMonth ) + '/01' ) as Period,
L_ProductType AS LocalCategory,
L_ProductCategory AS LocalSubcategory
FROM PMDelSpl;
**For i=1 to 11**
Join SELECT
'PMD' as RecType,
PMID as RecID,
CustomerID,
Quantity as Rolling12Packs,
Size * Quantity / 1000 AS Rolling12Litres,
(PMDelSpl.Method) as Method,
(PMDelSpl.Size) as Size,
(PMDelSpl.Shape) as Shape,
(PMDelSpl.System) as System,
(PMDelSpl.Type) as Type,
(PMDelSpl.Category) as Category,
(PMDelSpl.SubCat) as SubCat,
L_ProductType AS LocalCategory,
L_ProductCategory AS LocalSubcategory,
(PMDelSpl.Place) as Place,
PMDelSpl.Group,
PMDelSpl.Distribution,
datepart( month, dateadd( month, $(i), convert( datetime, str( PMYear ) + '/' + STR( PMMonth ) + '/01' ) ) ) as Month,
datepart( year, dateadd( month, $(i), convert( datetime, str( PMYear ) + '/' + STR( PMMonth ) + '/01' ) ) ) as Year,
dateadd( month, $(i), convert( datetime, str( PMYear ) + '/' + STR( PMMonth ) + '/01' ) ) as Period
FROM PMDelSpl
WHERE dateadd( month, $(i), convert( datetime, str( PMYear ) + '/' + STR( PMMonth ) + '/01' ) ) <GETDATE();
**Next i**

MySQL: Using alias in select arithmetic - Unknown field

Here's my select:
SELECT
SUM(t.amount + c.designFeeValue) as cashReceived,
ROUND(SUM(i.value) * (m.percentOurs / 100)) as adValue,
m.managementFee as managementFee,
m.productionCost as productionCost,
5 as emailAddress,
(
(
SELECT value
FROM commission_transactions
WHERE isDebit IS
TRUE
) -
(
SELECT value
FROM commission_transactions
WHERE isDebit IS
FALSE
)
) as miscExpenses,
(managementFee + productionCost + emailAddress + miscExpenses) as totalExpenses
This is bombing because of the following line, where I add up some aliases.
(managementFee + productionCost + emailAddress + miscExpenses) as totalExpenses
The aliases are unknown fields.
Is there a way I can keep the aliases for this arithmetic or do I need to re-do all the math that generates each alias for the calculation of totalExpenses? That seems like a very ugly way to do it.
UPDATE:
Per your suggestions, I am now using a derived table.
SELECT
cashReceived,
adValue,
managementFee,
productionCost,
emailAddress,
miscExpenses,
adValue + managementFee + productionCost + emailAddress + miscExpenses as totalExpenses
FROM (
SELECT
SUM(t.amount + c.designFeeValue) as cashReceived,
ROUND(SUM(i.value) * (m.percentOurs / 100)) as adValue,
m.managementFee as managementFee,
m.productionCost as productionCost,
5 as emailAddress,
(
(
SELECT value
FROM commission_transactions
WHERE isDebit IS TRUE
) -
(
SELECT value
FROM commission_transactions
WHERE isDebit IS FALSE
)
) as miscExpenses
FROM magazines m
JOIN insertions i ON i.magazineId = m.id
JOIN transactions t ON t.insertionId = i.id
JOIN contracts c ON i.contractId = c.id
JOIN commission_transactions ct ON m.id = ct.magazineId
WHERE m.id = 17
AND t.isChargedBack IS FALSE
AND t.`timestamp` >= '2013-08-01 00:00:00'
AND t.`timestamp` < '2013-09-01 00:00:00'
AND ct.createdDate >= '2013-08-01 00:00:00'
AND ct.createdDate < '2013-09-01 00:00:00'
) sub;
Aliases aren't available for re-use within the field list, e.g:
mysql> select 5 as five, five + 1 as six;
ERROR 1054 (42S22): Unknown column 'five' in 'field list'
You'll have to wrap the select with another one, then do your alias math in that wrapper, e.g.
select *, managementFee + productionCost + emailAddress + miscExpenses) as totalExpenses
FROM (
... your above query here ...
)

Select the most recent row from a log table using timestamp

I have a table for logging a Facebook application user actions. I want to get the latest row that is not older then 9 minutes for a specific action ID. The table has a lot of columns of other statistical information, so I will show only 2 of the rows that represent the problem:
timestamp facebookID producerID eventID actionID numOfTickets
2012-05-28 13:16:38 100003286974944 9 1741 cpf 2
2012-05-28 13:16:13 100003286974944 9 1741 cpf 4
What I want to do is getting the latest row where actionID = 'cpf'.
What I've tried is:
SELECT CONCAT_WS(' ', y.firstName, y.lastName) as fullName, x.facebookID, x.numOfTickets, MAX(x.timestamp)
FROM E4S_ANALYTICS.e4s_analytic_data x INNER JOIN E4S_FB.e4s_user_details y ON x.facebookID = y.facebookID
WHERE (x.actionID = 'CPF' AND x.numOfTickets > 0 AND x.producerID = 9 AND TIMEDIFF(NOW() , x.timestamp) < '00:09:00'
AND x.facebookID IN (SELECT facebookID FROM E4S_FB.e4s_session_data WHERE
TIMEDIFF(NOW() , sessionStart) < '00:09:00' ))
The result of the query is:
facebookID numOfTickets MAX(x.timestamp)
100003286974944 4 2012-05-28 13:16:38
The timestamp returned is correct but the numOfTickets is 4 instead of 2.
For note, the inner query:
SELECT facebookID FROM E4S_FB.e4s_session_data
WHERE TIMEDIFF(NOW() , sessionStart) < '00:09:00' ))
Is used to see who is still logged in to the application.
SELECT CONCAT_WS(' ', y.firstName, y.lastName) AS fullName,
x.facebookID,
x.numOfTickets,
x.timestamp
FROM (
SELECT *
FROM E4S_ANALYTICS.e4s_analytic_data
WHERE actionID = 'cpf'
AND numOfTickets > 0
AND producerID = 9
AND TIMEDIFF(NOW() , timestamp) < '00:09:00'
AND (facebookID, timestamp) IN (
SELECT facebookID, MAX(timestamp)
FROM E4S_ANALYTICS.e4s_analytic_data
WHERE actionID = 'cpf'
AND numOfTickets > 0
AND producerID = 9
AND TIMEDIFF(NOW() , timestamp) < '00:09:00'
AND facebookID IN (
SELECT facebookID
FROM E4S_FB.e4s_session_data
WHERE TIMEDIFF(NOW() , sessionStart) < '00:09:00'
)
GROUP BY facebookID
)
) AS x
INNER JOIN E4S_FB.e4s_user_details AS y USING (facebookID)
you can use order by timestamp desc to order the column according to latest first and then select the first row.
or try using max.
Have you tried not using MAX()?
Assuming you've checked JOIN and SUBQUERY results.
SELECT CONCAT_WS(' ', y.firstName, y.lastName) as fullName, x.facebookID, x.numOfTickets, MAX(x.timestamp)
FROM E4S_ANALYTICS.e4s_analytic_data x
INNER JOIN E4S_FB.e4s_user_details y ON x.facebookID = y.facebookID
GROUP BY x.facebookID
WHERE (x.actionID = 'CPF' AND x.numOfTickets > 0 AND x.producerID = 9 AND TIMEDIFF(NOW() , x.timestamp) < '00:09:00'
AND x.facebookID IN
(SELECT facebookID FROM E4S_FB.e4s_session_data
WHERE TIMEDIFF(NOW() , sessionStart) < '00:09:00' ))
ORDER BY x.timestamp DESC;

How to merge the result of this 2 queries in mysql server

I am actually stuck in merging the result of this two queries:
first query:
SELECT c.code, c.name, pc.sku, pc.cat_code, pp.title
FROM `cat_parent` cp, cat c, prod_cat pc, products pp
WHERE c.code = cp.cat_code
AND cp.cat_code = pc.cat_code
AND pp.sku = pc.sku
AND cp.parent_code = 01110
AND hide =0
The result I get is:
Second query:
SELECT `sku` , `update_date` , `description` , count( * ) AS total_sold
FROM `orderline`
WHERE `update_date` >= ( DATE_ADD(CURDATE( ) , INTERVAL -14 DAY ) )
AND `update_date` <= ( DATE_ADD(CURDATE( ) , INTERVAL -7 DAY ) )
GROUP BY left( sku, 7 )
ORDER BY total_sold DESC
The result:
The question I want to ask that how can I get the result by filtering the sku available in both tables.
Just bit confused on that part....any ideas will be appreciated.
This is only part of the data. there is heaps of data. Yes, I want to merge the both tables and want to find the common sku available in both tables.
My expected result will be sku, title, total sold.
Thanks, anyway I managed to get around to get the result.
My final query:
SELECT * FROM (
SELECT sku , update_date , description FROM orderline WHERE
update_date >= '2012-03-06' AND update_date <= '2012-03-07' )g
JOIN (
SELECT c.code, c.name, pc.sku, pc.cat_code FROM cat_parent cp, cat
c, prod_cat pc, products pp WHERE c.code = cp.cat_code AND cp.cat_code
= pc.cat_code AND pp.sku = pc.sku AND cp.parent_code =01110 AND hide =0 )p ON left( g.sku, 7 ) = left( p.sku, 7 )
Something like this -
SELECT
`c`.`code`, `c`.`name`, `pc`.`sku`, `pc`.`cat_code`, `pp.title`,
`ol`.`sku`, `ol`.`update_date`, `ol`.`description`, COUNT(*) AS `total_sold`
FROM `cat_parent` `cp`
INNER JOIN `cat` `c`
ON `c`.`code` = `cp`.`cat_code`
INNER JOIN `prod_cat` `pc`
ON `cp`.`cat_code` = `pc`.`cat_code`
INNER JOIN `products` `pp`
ON `pp`.`sku` = `pc`.`sku`
INNER JOIN `orderline` `ol`
ON LEFT(`pc`.`sku`, 7) = LEFT(`ol`.`sku`, 7)
WHERE `cp`.`parent_code` = 01110
AND `hide` = 0
AND `ol`.`update_date` >= ( DATE_ADD(CURDATE( ) , INTERVAL -14 DAY ) )
AND `ol`.`update_date` <= ( DATE_ADD(CURDATE( ) , INTERVAL -7 DAY ) )
GROUP BY left( `ol`.`sku`, 7 )
ORDER BY `total_sold` DESC