I'm trying to do multiple selects from one table but it only shown the last select statement.
CREATE PROCEDURE `usp_GetStockCard` (IN Matecode varchar(10))
BEGIN
(select tran_date as tran_date
from TM_matbalance
where Mate_code=Matecode);
(select Mate_code as Mate_code
from TM_matbalance
where Mate_code=Matecode);
(select tran_qtyx as Qty_in
from TM_matbalance
where tran_type='IN'
and mate_code=matecode);
(select tran_qtyx as Qty_out
from TM_matbalance
where tran_type='OUT'
and mate_code=matecode);
END
I've tried to change semicolon to comma after each select statement but it said that syntax error: missing 'semicolon'.
please help.
I look at your problem and I think I solve it.
Basically there is two problems here first one is to pivot your table where your Tran_Qtyx column become Qty_In and Qty_Out based on value in Tran_Type column (IN or OUT)... That part of problem you solve with this query
SELECT Tran_Date, Mate_Code,
SUM(CASE WHEN Tran_Type = 'IN' THEN Tran_Qtyx ELSE 0 END) Qty_In,
SUM(CASE WHEN Tran_Type = 'OUT' THEN Tran_Qtyx ELSE 0 END) Qty_Out
FROM myTable
WHERE Mate_Code = 'MAT001'
GROUP BY DATE(Tran_Date)
NOTE: In your desired result I only see 'MAT001'as Mate_Code so I stick with that in this solution and exclude MAT002 from result.
More about pivot table you can read here, there you can find a link, which is good to take a look, and where you can find a lot of stuff about mysql query's.
The second part of your problem is to get Qty_Balance column. Similar problem is solved here. It's how to calculate row value based on the value in previous row.
So your complete query could look like this:
SELECT t1.Tran_Date, t1.Mate_Code, t1.Qty_In, t1.Qty_Out,
#b := #b + t1.Qty_In - t1.Qty_Out AS Qty_Balance
FROM
(SELECT #b := 0) AS dummy
CROSS JOIN
(SELECT Tran_Date, Mate_Code,
SUM(CASE WHEN Tran_Type = 'IN' THEN Tran_Qtyx ELSE 0 END) Qty_In,
SUM(CASE WHEN Tran_Type = 'OUT' THEN Tran_Qtyx ELSE 0 END) Qty_Out
FROM myTable
WHERE Mate_Code = 'MAT001'
GROUP BY DATE(Tran_Date)) AS t1
ORDER BY t1.Tran_Date;
NOTE: probably only think you should change here is table name and it's should work.
Here is SQL Fiddle so you can see how that's work!
GL!
You will need to structure your query into one, or pass in a parameter to the stored procedure to select which output/query you want, to restructure your query you will need something like:
`CREATE PROCEDURE `usp_GetStockCard` (IN Matecode varchar(10))
BEGIN
(select tran_date as tran_date, Mate_code as Mate_code, tran_qtyx as Qty
from TM_matbalance
where Mate_code=Matecode
and (tran_type='IN' or tran_type='OUT');
END`
Or try this if you have an ID column:
SELECT coalesce(ta.id, tb.id) as tran_id, coalesce(ta.tran_date, tb.tran_date) as tran_date, coalesce(ta.Mate_code, tb.Mate_code) as Mate_code, ta.tran_type as Qty_In, tb.tran_type as Qty_Out
from (select ta.*
from TM_matbalance ta
where ta.tran_type = 'IN'
and Mate_code=Matecode
) ta full outer join
(select tb.*
from TM_matbalance tb
where tb.tran_type = 'OUT'
and Mate_code=Matecode
) tb
on ta.id = tb.id ;
just replace "id" with the name of your ID column if you don't need to return the id column then remove coalesce(ta.id, tb.id) as tran_id
Related
I will create a graph of population by gender every year, and the graph looks like the image below.
But I'm having a hard time with the query.
Query
SELECT
year_added,
COUNT(case when gender='Male' then 1 end) as malecount,
COUNT(case when gender='Female' then 1 end) as femalecount,
COUNT(*) as totalcount
FROM tbl
WHERE status = 1
GROUP BY year_added
Result
In the result, 2016 male count is 4 and female count is 8. In 2017, I want the male count of 2016 to be added on the male count on 2017, meaning 2017 male count will be 5, same with female count and total count. I provided an image below of what the result should look like. Can you help me how to do this for me to proceed on doing the graph? Or is there any other way to achieve this?
Try this:
SELECT
year_added,
#malecount_v := #malecount_v + malecount as malecount,
#femalecount_v := #femalecount_v + femalecount as femalecount,
#totalcount_v := #totalcount_v + totalcount as totalcount
FROM (
SELECT
year_added,
COUNT(case when gender='Male' then 1 end) as malecount,
COUNT(case when gender='Female' then 1 end) as femalecount,
COUNT(*) as totalcount
FROM tbl
WHERE status = 1
GROUP BY year_added
ORDER BY year_added
) t1
CROSS JOIN (SELECT #malecount_v := 0, #femalecount_v := 0, #totalcount_v := 0) t2
In Mysql you can do it with variables, like:
SELECT
year_added,
(#iMalecount := (COUNT(CASE WHEN gender = 'Male' THEN 1 END) + #iMalecount)) AS malecount,
(#iFemalecount := (COUNT(CASE WHEN gender = 'Female' THEN 1 END) + #iFemalecount)) AS femalecount,
(#iTotalcount := (COUNT(gender) + #iTotalcount)) AS totalcount
FROM tbl
WHERE status = 1
GROUP BY year_added
but is not 100% fiable as you can read in the documentation.
In other SQL flavour probably you need a stored procedure.
you can simply use
WITH TableCount AS
(
SELECT
year_added,
COUNT(case when gender='Male' then 1 end) as malecount,
COUNT(case when gender='Female' then 1 end) as femalecount,
COUNT(*) as totalcount
FROM tbl
WHERE status = 1
GROUP BY year_added
)
And after that use following query
SELECT
SUM(malecount) as 'malecount',
SUM(femalecount) as 'femalecount',
SUM(totalcount) as 'totalcount'
FROM TableCount
If you are using MySql you can use temporary table to do something like CTE
CREATE TEMPORARY TABLE IF NOT EXISTS TableCount AS (
SELECT
year_added,
COUNT(case when gender='Male' then 1 end) as malecount,
COUNT(case when gender='Female' then 1 end) as femalecount,
COUNT(*) as totalcount
FROM tbl
WHERE status = 1
GROUP BY year_added
)
And then you can use above query
SELECT
SUM(malecount) as 'malecount',
SUM(femalecount) as 'femalecount',
SUM(totalcount) as 'totalcount'
FROM TableCount
You can use the TEMPORARY keyword when creating a table. A TEMPORARY
table is visible only to the current session, and is dropped
automatically when the session is closed. This means that two
different sessions can use the same temporary table name without
conflicting with each other or with an existing non-TEMPORARY table of
the same name. (The existing table is hidden until the temporary table
is dropped.) To create temporary tables, you must have the CREATE
TEMPORARY TABLES privilege.
By using temporary table concept you can achieve common table expression kind of functionality in MySql
This is my table structure:
CUST_ID ORDER_MONTH
---------------------
1 1
1 5
2 3
2 4
My objective is to tag these customers as either New or Returning customers.
When I filter the query lets say for month 1 then customer 1 should have the tag 'New' but when I filter it for month 5 then customer 1 should show up as 'Return' as he already made a purchase in month 1.
Same way customer ID 2 should show up as New for month 3 and return for month 4.
I want to do this using a CASE statement and not inner join.
Thanks
If you insist on using a case statement, the logic would be something like "If this is the first month for that user, write new, otherwise write returning." The query would be as follows:
SELECT CASE
WHEN m.month = (SELECT MIN(month) FROM myTable WHERE customer = m.customer) THEN 'New'
ELSE 'Returning' END AS customerType
FROM myTable m;
However, I think this would be nicer and more readable in a JOIN. You can write an aggregation query to get the earliest month for each user, and then use COALESCE() to replace null values with 'Returning'. The aggregation:
SELECT customer, MIN(month) AS minMonth, 'New' AS customerType
FROM myTable
GROUP BY customer ;
To get the rest:
SELECT m.customer, m.month, COALESCE(t.customerType, 'Returning') AS customerType
FROM myTable m
LEFT JOIN(
SELECT customer, MIN(month) AS minMonth, 'New' AS customerType
FROM myTable
GROUP BY customer) t ON t.customer = m.customer AND t.minMonth = m.month;
Here is an SQL Fiddle example that shows both examples.
You don't need a JOIN and a case statement would probably be overkill...
SELECT CUST_ID, IF(COUNT(1)>1, 'Returning', 'New') AS blah
FROM the_table
WHERE ORDER_MONTH <= the_month
GROUP BY CUST_ID
;
Of course, using just month is going to cause problems after a year (or really, after passing December.)
This would be better
SELECT CUST_ID, IF(COUNT(1)>1, 'Returning', 'New') AS blah
FROM the_table
WHERE order_date <= some_date
GROUP BY CUST_ID
;
Well I do not reccomend this way but this is what you want.
select *
,case when order_month = (select MIN(order_month) from #temp t2 where t1.cust_ID =t2.cust_id) THEN 'NEW' ELSE 'Return' end 'Type'
from #temp t1
I think I get what you're trying to do. Your case statement basically just needs to check if the customer's month equals the month you're filtering by. Something like this:
SELECT
<your other fields>,
CASE WHEN Order_Month = <your filter> THEN 'New'
ELSE 'Return'
END AS 'SomeName'
FROM <your table>
Try this query
select a.CUST_ID, a.ORDER_MONTH ,case when b is not null then 'Return' else 'New' end as type
from tablename a
join tablename b on a.CUST_ID=b.CUST_ID and a.ORDER_MONTH>b.ORDER_MONTH
SELECT *,
CASE
WHEN EXISTS (SELECT *
FROM [YourTable] t2
WHERE t1.cust_id = t2.cust_id
AND t2.order_month < t1.order_month) THEN 'Return'
ELSE 'New'
END
FROM [YourTable] t1
This query uses CASE on an EXISTS clause.
The EXISTS is on a subquery which queries the same table for any rows in previous months.
If there are rows for previous months then the EXISTS is true and the CASE returns 'Return'. If there are no rows for previous months then the EXISTS is false and the CASE returns 'New'.
Here is my attendance table details Emp_ID(varchar),pdate(datetime),attendance(char(2))
i want to get the total count of attendence days ,total count of absent and total count of present in a single query for a particular date range grouping by emp_id
just an sample example to show you how to proceed with your data
declare #t table (id int,da date,attend Varchar(2))
insert into #t (id,da,attend) values (1,'20141011','P'),
(1,'20141012','A'),
(1,'20141013','P'),
(1,'20141014','A'),
(1,'20141014','P')
select ID,COUNT(da)Total,
(select COUNT(da) from #t where attend = 'A')as Absent,
(select COUNT(da) from #t where attend = 'P')as Present from #t
group by id
this worked for me.
select Emp_ID
,count(case when status ='A' then 1 end) as absent_count
,count(case when status ='P' then 1 end) as present_count
,count(distinct pdate) as Tot_count
from MASTERPROCESSDAILYDATA where pdate between '2014-01-01' and '2014-01-31'
group
by Emp_ID ;
You should try something like that
SELECT Emp_id, present, absent FROM details
NATURAL JOIN(
SELECT COUNT(*) AS present FROM details WHERE Emp_id = table.Emp_id AND attendence='P'
JOIN
SELECT COUNT(*) AS absent FROM details WHERE Emp_id = table.Emp_id AND attendence='A' ) AS ctt
You could use group by, as already demonstrated.
Or you can use window functions/analytic functions.
DECLARE #T TABLE (Emp_id INT,pdate DATE,attendance VARCHAR(2))
INSERT INTO #t (emp_id,pdate,attendance) VALUES (1,'20141011','P'),
(1,'20141012','A'),
(1,'20141013','P'),
(1,'20141014','A'),
(1,'20141014','P')
SELECT
DISTINCT
EMP_ID,
Attendance,
COUNT(*) OVER (PARTITION BY attendance) as CntAttendance
FROM
#t
Try the script below;
select id,
count(distinct pdate) as Total_Attendance_Days,
sum(case when attendance= 'p' then 1 else 0 end) Presents,
sum(case when att = 'a' then 1 else 0 end) Absents
from ##TT
where pdate between '01/04/2015' and '15/04/2015'
group by id
Hope this helps
table looks something like this: (yes those are & signs. ignore the dashes)
ID-VALUE-NUM
-1-YES----2-
-1-NO-----3-
-2-YES----1-
-2-NO-----1-
-3-&&&----1-
-3-&------2-
-3-&&-----2-
what I need to do:
for each ID, I need to get the value with the highest NUM, in the case of a tie and VALUE has &s then it would pick the shortest. if the value is YES/NO then it will pick YES.
result desired
ID-VALUE-NUM
-1-NO-----3-
-2-YES----1-
-3-&------2-
I think I have to put a IF statement in there somewhere but I'm not sure how.
Here is one way. The join finds the maximum num. Then the select uses logic to choose the right value based on your rules:
select t.id,
(case when count(*) = 1 then min(value)
when max(value like '%&%') > 0 then min(value)
when max(value = 'Yes') > 0 and max(value = 'No') > 0 then 'Yes'
else max(value)
end) as value,
t.num
from t join
(select id, max(num) as maxnum
from t
group by id
) tm
on t.id = tm.id and t.num = tm.maxnum
group by t.id, t.num
I'm trying to make a statistics page in my php script. in order to select the count from each table I need more than 30 Queries like this
SELECT COUNT(order_id) as `uncompleted_orders` FROM `orders` WHERE `order_status` != 0
and then I need to run another query like this:
SELECT COUNT(order_id) as `completed_orders` FROM `orders` WHERE `order_status` = 1
I've tried this approach, but it didn't work:
SELECT COUNT(order_id) as `uncompleted_orders` FROM `sd_orders` WHERE `order_status` != 4;
SELECT COUNT(order_id) as `completed_orders` FROM `sd_orders` WHERE `order_status` = 4;
Is there any way to creat a new temp table in MySQL contains the count for other tables?
You could try something like this:
SELECT
(
SELECT COUNT(order_id) FROM `sd_orders` WHERE `order_status` != 4
) as `uncompleted_orders`,
(
SELECT COUNT(order_id) FROM `sd_orders` WHERE `order_status` = 4
) as `completed_orders`
You will have a result set with one row and a field for each count.
Without more information it's impossible to generalise, but there are many constructs that can help you here.
First, your example is actually from one table, and not two. This means that you can do the following...
SELECT
COUNT(CASE WHEN order_status = 4 THEN order_id END) AS complete_orders,
COUNT(CASE WHEN order_status <> 4 THEN order_id END) AS incomplete_orders
FROM
sd_orders
This works because COUNT(<something>) doesn't include an NULLs in the results. And by not including an ELSE clause, anything that doesn't match returns NULL. Another way people accomplish the same result is SUM(CASE WHEN ? THEN 1 ELSE 0 END).
Second, where you do actually have multiple tables, you can combine the results in several different ways...
-- Where you want one value from each table...
--------------------------------------------------------------------------------
SELECT
(SELECT COUNT(*) FROM table1 WHERE fieldx = ?) AS value1,
(SELECT COUNT(*) FROM table2 WHERE fieldy = ?) AS value2
-- Where you want one row of values from each table...
--------------------------------------------------------------------------------
SELECT
table1_summary.value1 AS table1_value1,
table1_summary.value2 AS table1_value2,
table2_summary.value1 AS table2_value1,
table2_summary.value2 AS table2_value2
FROM
(
SELECT
COUNT(CASE WHEN fieldx = ? THEN id END) AS value1,
COUNT(CASE WHEN fieldx <> ? THEN id END) AS value2
FROM
table1
)
AS table1_summary
CROSS JOIN
(
SELECT
COUNT(CASE WHEN fieldy = ? THEN id END) AS value1,
COUNT(CASE WHEN fieldy <> ? THEN id END) AS value2
FROM
table2
)
AS table2_summary
-- Where you want many rows, but of the same fields, from each table...
--------------------------------------------------------------------------------
SELECT
*
FROM
(
SELECT
'Table1' AS source_table,
fielda AS some_grouping,
COUNT(CASE WHEN fieldx = ? THEN id END) AS value1,
COUNT(CASE WHEN fieldx <> ? THEN id END) AS value2
FROM
table1
GROUP BY
fielda
UNION ALL
SELECT
'Table2' AS source_table,
fieldb AS some_grouping,
COUNT(CASE WHEN fieldy = ? THEN id END) AS value1,
COUNT(CASE WHEN fieldy <> ? THEN id END) AS value2
FROM
table2
GROUP BY
fieldb
)
AS summary
ORDER BY
source_table,
some_grouping,
value1,
value2
As you can see, there are a lot of ways to do this. How you approach it totally depends on your data and your needs.