I have been working with SAP Business One right now, and at this moment i was baffled on how to achieve the required query output.
The desired output will be like
SLPName | Customer Name | Jan | Jan-chrgs | Feb | Feb-chrgs | Mar | Mar-chrgs
slp1 | cust1 | 123.00 | 30.00 | 230.00 | 40.00 | 150.00 | 35.00
What have done so far is this, which works perfectly BUt without charges(delivery charges, repair charges, etc.).
SELECT SRNAMe, Customer,
ISNULL([1],0) as [Jan],
ISNULL([2],0) as [Feb],
ISNULL([3],0) as [Mar],
ISNULL([4],0) as [Apr]
FROM (SELECT T2.SlpName SRNAMe,T1.CARDNAME Customer, SUM(T1.DocTotal) as Total,MONTH(T1.Docdate) as [month]
FROM ORDR T1 INNER JOIN OSLP T2 ON T2.SlpCode=T1.SlpCode
LEFT OUTER JOIN RDR3 T3 ON T3.DocEntry=T1.DocEntry
WHERE T1.DocDate BETWEEN '1.1.17' AND '4.30.17'
AND T1.CANCELED='N' AND T1.U_StatusCancel='N'
GROUP BY T2.SlpName,T1.CardName, T1.DocDate) S
PIVOT (SUM(S.[Total]) FOR [month] IN ([1],[2],[3],[4])
) P Order By P.SRNAME, P.Customer
The logic that i was thinking was
SELECT SRNAMe, Customer,
ISNULL([1],0) as [Jan], column as jan-chrg,
ISNULL([2],0) as [Feb], column as feb-chrg,
ISNULL([3],0) as [Mar], column as mar-chrg,
ISNULL([4],0) as [Apr], column as apr-chrg
and i dont know the rest, maybe put those total charges inside pivot but, seems not gonna work.
please help, if you are getting what i want. Thanks
After meditating day and night, i finally found the answer my self. And hope this helps you guys as well(you know, for ideas).
SELECT SRNAMe, Customer,
ISNULL([1],0) as [Jan], ISNULL(jancharge,0) as [Charge],
ISNULL([2],0) as [Feb], ISNULL(febcharge,0) as [Charge],
ISNULL([3],0) as [Mar], ISNULL(marcharge,0) as [Charge],
ISNULL([4],0) as [Apr], ISNULL(jancharge,0) as [Charge]
FROM (SELECT T2.SlpName SRNAMe,T1.CARDNAME Customer, (SELECT TOP 1 T9.TotalSumSy FROM RDR3 T9 INNER JOIN ORDR T8 ON T8.DocEntry=T9.DocEntry WHERE MONTH(T8.DocDate)=1 AND T8.CardName=T1.CardName) jancharge,
(SELECT TOP 1 T9.TotalSumSy FROM RDR3 T9 INNER JOIN ORDR T8 ON T8.DocEntry=T9.DocEntry WHERE MONTH(T8.DocDate)=2 AND T8.CardName=T1.CardName) febcharge,
(SELECT TOP 1 T9.TotalSumSy FROM RDR3 T9 INNER JOIN ORDR T8 ON T8.DocEntry=T9.DocEntry WHERE MONTH(T8.DocDate)=3 AND T8.CardName=T1.CardName) marcharge,
(SELECT TOP 1 T9.TotalSumSy FROM RDR3 T9 INNER JOIN ORDR T8 ON T8.DocEntry=T9.DocEntry WHERE MONTH(T8.DocDate)=4 AND T8.CardName=T1.CardName) aprcharge, SUM(T1.DocTotal) as Total,MONTH(T1.Docdate) as [month]
FROM ORDR T1 INNER JOIN OSLP T2 ON T2.SlpCode=T1.SlpCode
LEFT OUTER JOIN RDR3 T3 ON T3.DocEntry=T1.DocEntry
WHERE T1.DocDate BETWEEN '1.1.17' AND '4.30.17'
AND T1.CANCELED='N' AND T1.U_StatusCancel='N'
GROUP BY T2.SlpName,T1.CardName, T1.DocDate) S
PIVOT (SUM(S.[Total]) FOR [month] IN ([1],[2],[3],[4])
) P Order By P.SRNAME, P.Customer
Related
I have two tables as follow:
table internetclient
(id,full_name,location,phone_number)
table internetclientdetails
(incdid,icid,date_sub, date_exp,isPaid,profile_sub)
the data in two table is as follow:
client
--------------------------------------------------------
id full_name location phone_number
-------------------------------------------------------
4 Joe Amine beirut 03776132
5 Mariam zoue beirut 03556133
client_subscription
--------------------------------------------------------------------------
incdid icid date_sub date_exp isPaid sub_price
----------------------------------------------------------------------------
6 4 2018-01-01 2018-01-30 0 2000
7 5 2017-01-01 2017-01-30 0 1000
8 4 2018-03-01 2018-03-30 1 50000
9 5 2018-05-01 2019-05-30 1 90000
note : incdid stands for internetClientDetailsId
and icid stands for internetClientId
Problem
I want to make a query that return client name along with all details depending on the latest client subscription date, the result should be as follow:
------------------------------------------------------------
full_name client_id date_sub sub_price
------------------------------------------------------------
Joe Amine 4 2018-03-01 50000
Mary 5 2018-05-01 90000
What i am tring
SELECT * FROM client c LEFT JOIN client_subscription c_s on c.id=c_s.client_id
UNION
SELECT * FROM client c RIGHT JOIN client_subscription c_S on c.id=c_s.client_id
WHERE
c.sub_date=(SELECT MAX(sub_date) from client_subscription c_s INNER JOIN client c on c.id=c_s.client_id GROUP BY c_s.client_id
i have been working on it all the night. Any help is appreciated a lot.
To get client_subscription for each client you could use a self join
select c.name, a.client_id, a.date_sub, a.sub_price
from client_subscription a
join (
select client_id, max(date_sub) date_sub
from client_subscription
group by client_id
) b on a.client_id = b.client_id and a.date_sub = b.date_sub
join client c on a.client_id = c.id
order by a.date_sub
Demo
Or using left join
select c.name, a.client_id, a.date_sub, a.sub_price
from client_subscription a
left join client_subscription b on a.client_id = b.client_id and a.date_sub < b.date_sub
join client c on a.client_id = c.id
where b.client_id is null
order by a.date_sub
Demo
Using your updated data set updated queries are
select c.full_name, a.icid, a.date_sub, a.sub_price
from internetclientdetails a
join (
select icid, max(date_sub) date_sub
from internetclientdetails
group by icid
) b on a.icid = b.icid and a.date_sub = b.date_sub
join internetclient c on a.icid = c.id
order by a.date_sub;
select c.full_name, a.icid, a.date_sub, a.sub_price
from internetclientdetails a
left join internetclientdetails b on a.icid = b.icid and a.date_sub < b.date_sub
join internetclient c on a.icid = c.id
where b.icid is null
order by a.date_sub
Updated Demo
Hi try below sample might help you.
DECLARE #tblClient AS TABLE (ID INT , Name varchar(100))
DECLARE #tblClientSub As TABLE (id INT,client_id INT,date_sub DATE,sub_price INT)
INSERT INTO #tblClient (id,Name)
VALUES
(1,'Linda'),
(2,'Mary'),
(3,'Joe')
INSERT INTO #tblClientSub(Id,client_id , date_sub , sub_price)
VALUES
(1,1,'2018/01/01',50),
(2,2,'2018/02/01',50),
(3,2,'2018/03/01',30),
(4,2,'2018/04/01',30),
(5,3,'2018/01/01',50),
(6,3,'2018/07/01',50),
(7,1,'2018/02/01',40)
SELECT c.Id,c.Name,cs.date_sub,cs.sub_price
FROM #tblClient c
CROSS APPLY (SELECT TOP (1)date_sub,sub_price
FROM #tblClientSub
WHERE client_id = c.Id
ORDER BY date_sub DESC) cs
select c.name as 'client_name',cs.client_id,max(cs.sub_date) as 'date_sub',cs.sub_price from client c ,
client_subscription cs where cs.client_id=c.id group by cs.client_id,cs.sub_price;
Try this
SELECT c.Name, c.id , MAX(date_sub), sub_price FROM client c LEFT JOIN client_subscription c_s on c.id=c_s.client_id
GROUP BY c.id
ORDER BY c.id ASC
Tables in SQL Query
Likes(cname, pizza)
Customers(cname, area)
Restaurants(rname, area)
Sells (rname, pizza, price)
Refer to: http://sqlfiddle.com/#!9/06ade3/6 (Consist of code and database schema)
Expected Results
| rname |
---------
| D |
| L |
--> Output a list all restaurants R such that there does not exist any restaurant R2 that is more diverse than R.)
A restaurant is more diverse if:
priceRange of R1 >= priceRange of R2 AND numPizza of R1 > numPizza of R2
OR
priceRange of R1 > priceRange of R2 AND numPizza of R1 >= numPizza of R2
If the restaurant does not sell any pizza, numPizza = 0 and priceRange = 0
** priceRange refers to max-min of the restaurant.
** numPizza refers to total number of pizza in the restaurant
My SQL Code:
SELECT r1.rname
FROM restaurants r1
INNER JOIN restaurants r2 ON r1.rname < r2.rname
WHERE (SELECT (MAX(s1.price)-MIN(s1.price) AS s1.pricerange)
FROM sells s1
INNER JOIN sells s2 ON s1.rname < s2.rname)
WHERE s1.pricerange > MAX(s1.price)-MIN(s1.price) AS s2.pricerange
AND COUNT(s1.pizza) >= COUNT(s2.pizza)
)
OR (SELECT (MAX(s1.price)-MIN(s1.price) AS s1.pricerange)
FROM sells s1
INNER JOIN sells s2 ON s1.rname < s2.rname)
WHERE s1.pricerange >= MAX(s1.price)-MIN(s1.price) AS s2.pricerange
AND COUNT(s1.pizza) > COUNT(s2.pizza)
)
The way that i implement it seems to be wrong. The last part of my code looks really similar to the second last part. Except for the inequality signs. Is there a better way to do this?
Create a temporary table such as below then run the query. The logic can be simplified as "collect all restaurants having maximum pricerange or maximum numpizza. Hope this helps. Thanks.
CREATE TEMPORARY TABLE IF NOT EXISTS table2 AS
(select r.rname,
max(s.price)-min(s.price) as pricerange,
count(1) as numpizzas
from restaurants r
inner join sells s on r.rname=s.rname
inner join pizzas p on s.pizza=p.pizza
group by r.rname)
SQL:
select t1.rname
from table2 t1
inner join (
select max(pricerange) as maxpricerange
from table2) t2 on t1.pricerange=t2.maxpricerange
union
select t1.rname
from table2 t1
inner join (
select max(numpizzas) as maxnumpizzas
from table2) t2 on t1.numpizzas=t2.maxnumpizzas
Result:
rname
D
L
I have the code below but i want to arrange it by date_available desc and group it by store_id so that i will only return 1 value.
SELECT
product_to_store.store_id,
product.date_available,
product.product_id,
product_description.name,
product_to_category.category_id,
pcd3.name,
lvl2.parent_id,
pcd2.name,
CASE
WHEN lvl2.parent_id > 0 THEN lvl1.parent_id
ELSE 0
END,
pcd1.name,
product.quantity,
product_type.type
FROM product
inner join product_to_store on (product.product_id=product_to_store.product_id)
inner join product_description on (product.product_id = product_description.product_id)
inner join product_to_category on (product.product_id = product_to_category.product_id)
inner join product_type on (product.product_id = product_type.product_id)
inner join store on (product_to_store.store_id = store.store_id)
inner join product_category as lvl2 on (product_to_category.category_id = lvl2.category_id)
inner join product_category as lvl1 on (lvl1.category_id = lvl2.parent_id)
inner join product_category_description as pcd3 on (pcd3.category_id = lvl2.category_id)
inner join product_category_description as pcd2 on (pcd2.category_id = lvl2.parent_id)
inner join product_category_description as pcd1 on (pcd1.category_id = lvl1.parent_id)
Sample table:
store_id date_available name
1 2017-05-04 T1
1 0000-00-00 T2
2 2017-06-04 T3
3 0000-00-00 T4
2 2017-04-04 T5
3 0000-00-00 T6
Expected result:
store_id date_available name
1 2017-05-04 T1
2 2017-06-04 T3
3 0000-00-00 T4
How can i do that in mysql? Please help me thank you.
Use this as a hint:
-- Create some testing data
IF OBJECT_ID('tempdb..#product') IS NOT NULL DROP TABLE #product
CREATE TABLE #product(
[store_id] int
,[date_available] varchar(50)
,[name] varchar(50)
)
INSERT INTO #product VALUES
(1, '2017-05-04', 'T1')
,(1, '0000-00-00', 'T2')
,(2, '2017-06-04', 'T3')
,(3, '0000-00-00', 'T4')
,(2, '2017-04-04', 'T5')
,(3, '0000-00-00', 'T6')
-- Get result
SELECT p1.[store_id], p1.[date_available], MIN(p2.[name]) AS [name]
FROM (
SELECT [store_id], MAX([date_available]) AS [date_available] FROM #product
GROUP BY [store_id]
) p1
INNER JOIN #product p2
ON p1.[store_id] = p2.[store_id] AND p1.[date_available] = p2.[date_available]
GROUP BY p1.[store_id], p1.[date_available]
-- Destroy the temp table
DROP TABLE #product
Then in your long script, you may rewrite it to something like this:
SELECT product_to_store.store_id,
product.date_available,
product.product_id,
.
.
.
FROM product
INNER JOIN ...
INNER JOIN ...
INNER JOIN (
SELECT p1.[store_id], p1.[date_available], MIN(p2.[name]) AS [name]
FROM (
SELECT [store_id], MAX([date_available]) AS [date_available] FROM #product
GROUP BY [store_id]
) p1
INNER JOIN #product p2
ON p1.[store_id] = p2.[store_id] AND p1.[date_available] = p2.[date_available]
GROUP BY p1.[store_id], p1.[date_available]
) store ON (product_to_store.store_id = store.store_id)
INNER JOIN ...
INNER JOIN ...
I've got a SELECT with multiple JOINS for a paginated Tableview. In general this is working for unfiltered results.
The query looks like this:
SELECT seltable.*,
tbl2.name AS tbl2name,
tbl3.name AS tbl3name,
tbl4.name AS tbl4name
FROM
( SELECT * FROM selecttable
WHERE value = 99
ORDER BY datetime DESC
LIMIT 50 OFFSET 0 )
AS seltable
LEFT JOIN table1 AS tbl1 ON seltable.tbl1_uid = tbl1.uid
LEFT JOIN table2 AS tbl2 ON tbl1.tbl2_uid = tbl2.uid
LEFT JOIN table3 AS tbl3 ON tbl2.tbl3_uid = tbl3.uid
LEFT JOIN table4 AS tbl4 ON tbl3.tbl4_uid = tbl4.uid;
Now I've got no clue how to accomplish filtering the results with a condition related to one of the join tables.
When I just set a:
LEFT JOIN tablex AS table ON foreign_table.tblx_uid = table.uid AND {condition}
this condition regards only to the 50 results of the nested SELECT.
Is there any way to achieve using WHERE clauses on the JOIN tables in this scenario?
For sample data see http://sqlfiddle.com/#!2/fad4d/2
Expected results:
to get x team records limited to 5 team uids, where Tournament2 is one of the related tournaments for the team.
Best regards
w1ll1
Try not controlling the pagination in that subquery, instead just use a more conventional query with a composite where clause. HOWEVER, because you are using left joins take care adding filters through the where clause that would override the outer join to produce the effect of an inner join.
SELECT seltable.*,
tbl2.name AS tbl2name,
tbl3.name AS tbl3name,
tbl4.name AS tbl4name
FROM selecttable AS seltable
LEFT JOIN table1 AS tbl1 ON seltable.tbl1_uid = tbl1.uid
LEFT JOIN table2 AS tbl2 ON tbl1.tbl2_uid = tbl2.uid
LEFT JOIN table3 AS tbl3 ON tbl2.tbl3_uid = tbl3.uid
LEFT JOIN table4 AS tbl4 ON tbl3.tbl4_uid = tbl4.uid
WHERE seltable.value = 99
...
ORDER BY seltable.datetime DESC
LIMIT 50 OFFSET 0
Alternatively use more subqueries, like this:
SELECT seltable.*,
tbl2.name AS tbl2name,
tbl3.name AS tbl3name,
tbl4.name AS tbl4name
FROM
( SELECT * FROM selecttable
WHERE value = 99
ORDER BY datetime DESC
LIMIT 50 OFFSET 0 )
AS seltable
LEFT JOIN ( SELECT uid, name
FROM table1
WHERE 1=1 -- amend to suit
) AS tbl1 ON seltable.tbl1_uid = tbl1.uid
LEFT JOIN ( SELECT uid, name
FROM table2
WHERE 1=1 -- amend to suit
) AS tbl2 ON tbl1.tbl2_uid = tbl2.uid
LEFT JOIN ( SELECT uid, name
FROM table3
WHERE 1=1 -- amend to suit
) AS tbl3 ON tbl2.tbl3_uid = tbl3.uid
LEFT JOIN ( SELECT uid, name
FROM table4
WHERE 1=1 -- amend to suit
) AS tbl4 ON tbl3.tbl4_uid = tbl4.uid;
Here is another attempt, based on your sqlfiddle it appears that INNER JOINS may be used:
SELECT theteam.*,
trnmnt.name AS tournamentname,
cat.name AS categoryname,
sport.name AS sportname
FROM (
SELECT * FROM team
ORDER BY team.name ASC )
AS theteam
INNER JOIN tournament_team AS tntm ON tntm.team_uid = theteam.uid
INNER JOIN tournament AS trnmnt ON tntm.tournament_uid = trnmnt.uid AND trnmnt.name = 'Tournament2'
INNER JOIN category AS cat ON trnmnt.category_uid = cat.uid
INNER JOIN sport ON cat.sport_uid = sport.uid
LIMIT 5 OFFSET 0
;
The result of that query is:
| UID | NAME | TOURNAMENTNAME | CATEGORYNAME | SPORTNAME |
|-----|--------|----------------|--------------|-----------|
| 2 | Team02 | Tournament2 | Germany | Soccer |
| 3 | Team03 | Tournament2 | Germany | Soccer |
| 4 | Team04 | Tournament2 | Germany | Soccer |
| 5 | Team05 | Tournament2 | Germany | Soccer |
| 6 | Team06 | Tournament2 | Germany | Soccer |
I am unable to get sum() after joining 2 tables, one is HEADER AND DETAIL. It just gives only 0 result for the below sql statement. Need some help:
My tables:
INVHDR:
Invno, Invdate, Ac_code
100 2013-04-01 2
101 2013-04-30 2
INVDTLS:
Invno, Prod_desc, Amount
100 Argon 155
100 Argon 250
101 Oxygen 322
101 Oxygen 065
Desired result:
Sum of amts: 405
MYSQL statement to inner join and sum()
SELECT
a.Invno, a.Ac_code, a.Invdate, b.*
FROM INVHDR a
INNER JOIN (
SELECT
Invno, Prod_desc, SUM( Amount ) AS amts
FROM INVDTLS
WHERE Prod_desc='Argon'
) AS b ON a.Invno = b.Invno
WHERE
a.Ac_code='2'
AND a.Invdate BETWEEN '2013-04-01'
AND '2013-04-30'
GROUP BY a.Ac_code
Why are you writing such a complicated Query, try this:
SELECT sum(b.Amount)
FROM INVHDR a
INNER JOIN INVDTLS b
ON a.Invno = b.Invno
WHERE a.Ac_code='2'
AND a.Invdate BETWEEN '2013-04-01' AND '2013-04-30'
AND b.Prod_desc='Argon'
--Group by b.Prod_desc,a.Invno, a.Ac_code
Here is the SQL Fiddle
check http://www.sqlfiddle.com/#!2/86377/8 Thank you #Luv
SELECT
a.Invno, a.Ac_code, b.Prod_desc, SUM(b.Amount) AS Amount
FROM INVHDR a
INNER JOIN INVDTLS b ON a.Invno = b.Invno
WHERE
a.Ac_code = 2 -- a.Ac_code='2'
AND a.Invdate BETWEEN '2013-04-01' AND '2013-04-30'
AND b.Prod_desc='Argon'
group by a.Invno, a.Ac_code, b.Prod_desc