Combining the result of two queries to one result SQL - sql-server-2008

I'm trying t create a compare, now i'm only able to make it as multiple result (two different result).
both of the result above is from two queries.
My first result query
SELECT
customercode,
CONVERT(DATE, TransDate) transdate,
SUM(TotalReceivable) AS total
FROM
SalesOrderHeader
WHERE
CustomerCode = 'K-MDMM4'
AND TransDate BETWEEN '2016-07-25' AND '2016-07-30'
GROUP BY
CONVERT(DATE, TransDate), customercode
and my second query
SELECT
b.OutletCode AS outlet,
tanggal,
(cash + cc + dc + flash + piutang + reject + disc50 +
isnull(spesial_item,0)) total
FROM
transaksi a
LEFT JOIN
Outlet b ON a.Outlet = b.OutletCode
LEFT JOIN
area c ON b.areacode = c.areacode
WHERE
b.active = 1
AND b.OutletCode LIKE 'K-MDMM4'
AND flag = 1
AND tanggal BETWEEN '2016-07-25' AND '2016-07-30'
GROUP BY
b.OutletCode, tanggal, cash, cc, dc, flash,
piutang, reject, disc50, spesial_item, ba, mpm, tf,
ul,remarks
ORDER BY
tanggal DESC
I want this result.
customercode | transdate | total_tbl1 | total_tbl2
K-MDMM4 2016-07-25 6004050 6004050
K-MDMM4 2016-07-26 6880340 6880340
K-MDMM4 2016-07-27 5745040 5745040
K-MDMM4 2016-07-28 7424820 7424820
I can't use jsfiddle :(. I don't know why. I can't create table via queries.
From now, I have this query
SELECT
b.OutletCode AS outlet,
tanggal,
(cash + cc + dc + flash + piutang + reject + disc50 +
isnull(spesial_item, 0)) total,
SUM(d.TotalReceivable) AS total
FROM
transaksi a
LEFT JOIN
Outlet b ON a.Outlet = b.OutletCode
LEFT JOIN
area c ON b.areacode = c.areacode
LEFT JOIN
salesorderheader d ON CONVERT(DATE, a.tanggal) = CONVERT(DATE, d.transdate)
WHERE
b.active = 1
AND b.BrandCode LIKE '%%'
AND b.OutletCode LIKE '%%'
AND flag = 1
AND YEAR(tanggal) = '2016'
AND MONTH(tanggal) = '7'
AND outlet = 'K-MDMM4'
GROUP BY
OutletCode, tanggal, cash, cc, dc, flash,
piutang, reject, disc50, spesial_item, transdate, totalreceivable
ORDER BY
tanggal DESC
and the result so far from my desired result....

Combine both queries into a single join and select
SELECT tbl1.customercode,
CAST(tbl1.transdate AS DATE) AS transdate,
tbl1.total AS total_tbl1,
tbl2.total AS total_tbl2
FROM
(
-- Query 1
SELECT customercode,convert(date,TransDate) transdate,SUM(TotalReceivable) as total
FROM SalesOrderHeader
where CustomerCode = 'K-MDMM4'
and TransDate between '2016-07-25' and '2016-07-30'
group by convert(date,TransDate),customercode
) AS tbl1
INNER JOIN (
-- Query 2
select b.OutletCode as outlet,tanggal, (cash + cc + dc + flash + piutang + reject + disc50 +
isnull(spesial_item,0)) total From transaksi a
left join Outlet b on a.Outlet = b.OutletCode
left join area c on b.areacode = c.areacode
where b.active = 1 and b.OutletCode like 'K-MDMM4' and flag = 1 and tanggal
between '2016-07-25' and '2016-07-30'
group by b.OutletCode,tanggal,cash,cc,dc,flash,piutang,reject,disc50,spesial_item,ba,mpm,tf,ul,remarks
) AS tbl2 ON tbl2.outlet = tbl1.customercode AND CAST(tbl2.trnggal AS DATE) = CAST(tbl1.transdate AS DATE)
order by CAST(tbl1.transdate AS DATE) DESC;

I don't have a database installed on this PC but what you're looking for is:
SELECT val1, val2 FROM
(SELECT1_of_your_code AS table1) INNER JOIN
(SELECT2_of_your_code AS table2) ON
table1.x == table2.y

Related

How to group by date

Below I cannot do Group by Date the following figures.
I have tried to put Group By in different lines, but not working.
SELECT SUM(a.NetAmount) AS TotalDonation
FROM (
SELECT
(
CASE WHEN bt.BalanceTransactionCurrencyID = 17
THEN bt.BalanceTransactionNet
ELSE
bt.BalanceTransactionNet * (SELECT TOP 1 ExrateValue FROM Exrate WHERE ExrateDate < bt.BalanceTransactionCreated AND bt.BalanceTransactionCurrencyID = CurrencyID ORDER BY ExrateDate Desc)
END
) AS NetAmount
FROM Charge as ch
JOIN BalanceTransaction as bt ON (ch.BalanceTransactionID = bt.BalanceTransactionID)
WHERE ch.ChargeCreatedDate BETWEEN '3-1-2019' AND '3-31-2019'
) AS a
I wanted to see:
Days Total Amount
March 1 xxxx
March 2 xxxx
March 3 xxx
MySQL does not use TOP. Use LIMIT:
SELECT ChargeCreatedDate, SUM(netamount)
FROM (SELECT ch.ChargeCreatedDate,
(CASE WHEN bt.BalanceTransactionCurrencyID = 17
THEN bt.BalanceTransactionNet
ELSE bt.BalanceTransactionNet * (SELECT e.ExrateValue
FROM Exrate e
WHERE e.ExrateDate < bt.BalanceTransactionCreated AND
e.CurrencyID = bt.BalanceTransactionCurrencyID
ORDER BY ExrateDate Desc
LIMIT 1
)
END) AS NetAmount
FROM Charge ch JOIN
BalanceTransaction bt
ON ch.BalanceTransactionID = bt.BalanceTransactionID
WHERE ch.ChargeCreatedDate BETWEEN '2019-03-01' AND '2019-03-31'
) chtbt
GROUP BY ChargeCreatedDate;
If you happen to be using SQL Server, you can replace the LIMIT 1 with FETCH FIRST 1 ROW ONLY.
The following code will hopefully display what you are looking for
SELECT a.Days AS Days, SUM(cast(a.NetAmount as decimal(16,9))) AS TotalDonation
FROM (
SELECT
(
CASE WHEN bt.BalanceTransactionCurrencyID = 17
THEN bt.BalanceTransactionNet
ELSE
bt.BalanceTransactionNet * (SELECT TOP 1 ExrateValue FROM Exrate WHERE ExrateDate < bt.BalanceTransactionCreated AND bt.BalanceTransactionCurrencyID = CurrencyID ORDER BY ExrateDate Desc)
END
) AS NetAmount,
ch.ChargeCreatedDate as Days
FROM Charge as ch
JOIN BalanceTransaction as bt ON (ch.BalanceTransactionID = bt.BalanceTransactionID)
WHERE ch.ChargeCreatedDate BETWEEN '3-1-2019' AND '3-31-2019'
) AS a GROUP BY a.Days
This should be sufficient. You need to SELECT the desired value in the query in order to get it to show up. Also when using the SUM() function you need to specify what the group value will be.

MySQL OUTER Join with AS

I have quite the beast of a SQL statement and I was hoping for a little help. I have found that I need to be using an OUTER join for some of these tables but MySQL doesn't have that function.
SELECT validclick.CampaignName AS CampaignName,
validclick.Website AS Website,
validclick.RevClicks AS RevClicks,
validclick.Revenue AS Revenue,
validclick.TQ AS TQ,
validclick.Source AS Source,
validclick.ScoredClicks AS ScoredClicks,
validclick.Searches AS Searches,
vci.Impressions AS Impressions,
(validclick.RevClicks / validclick.Searches * 100) AS CTR,
(IFNULL(yaho.Spend, 0) + IFNULL(facebook.Spend, 0) + IFNULL(google.Spend, 0)) AS Spend,
(IFNULL(yaho.PaidClicks, 0) + IFNULL(facebook.PaidClicks, 0) + IFNULL(google.PaidClicks, 0)) AS PaidClicks,
(validclick.Revenue -
(IFNULL(yaho.Spend, 0) + IFNULL(facebook.Spend, 0) + IFNULL(google.Spend, 0))) AS Profit,
(validclick.TQ / validclick.ScoredClicks) AS ScoredTQ,
(validclick.TQ / validclick.RevClicks) AS UnscoredTQ,
(validclick.Revenue /
(IFNULL(yaho.PaidClicks, 0) + IFNULL(facebook.PaidClicks, 0) + IFNULL(google.PaidClicks, 0))) AS RPI,
(validclick.Revenue / validclick.RevClicks) AS RPC,
((IFNULL(yaho.Spend, 0) + IFNULL(facebook.Spend, 0) + IFNULL(google.Spend, 0)) /
(IFNULL(yaho.PaidClicks, 0) + IFNULL(facebook.PaidClicks, 0) + IFNULL(google.PaidClicks, 0))) AS CPC,
((validclick.Revenue -
(IFNULL(yaho.Spend, 0) + IFNULL(facebook.Spend, 0) + IFNULL(google.Spend, 0))) /
(IFNULL(yaho.Spend, 0) + IFNULL(facebook.Spend, 0) + IFNULL(google.Spend, 0)) * 100) AS ROI,
(validclick.RevClicks /
(IFNULL(yaho.PaidClicks, 0) + IFNULL(facebook.PaidClicks, 0) + IFNULL(google.PaidClicks, 0)) * 100) AS Conversion
FROM
(SELECT camp.CampaignName AS CampaignName,
MAX(camp.Website) AS Website,
MAX(camp.Source) AS Source,
SUM(vc.Clicks) AS RevClicks,
SUM(vc.Revenue) AS Revenue,
SUM(vc.TQ) AS TQ,
SUM(vc.ScoredClicks) AS ScoredClicks,
SUM(vc.BiddedSearches) AS Searches
FROM
(SELECT AffID,
MAX(CampaignName) AS CampaignName,
Website,
MAX(Source) AS Source
FROM campaigns
GROUP BY AffID) AS camp
JOIN
(SELECT AffID,
SUM(Clicks) AS Clicks,
SUM(AffiliateRevenue) AS Revenue,
SUM(BiddedSearches) AS BiddedSearches,
SUM(CASE WHEN TQ > 0 THEN (TQ * Clicks) ELSE NULL END) AS TQ,
SUM(CASE WHEN TQ > 0 THEN Clicks ELSE NULL END) AS ScoredClicks
FROM validclickvc
WHERE Date BETWEEN '2018-05-06' AND '2018-05-07'
GROUP BY AffID) AS vc
ON vc.AffID = camp.AffID
GROUP BY camp.CampaignName) AS validclick
LEFT JOIN
(SELECT CampaignName,
SUM(Spend) AS Spend,
SUM(OutboundClicks) AS PaidClicks
FROM facebookads
WHERE Date BETWEEN '2018-05-06' AND '2018-05-07'
GROUP BY CampaignName) AS facebook
ON validclick.CampaignName = facebook.CampaignName
LEFT JOIN
(SELECT CampaignName,
SUM(Spend) AS Spend,
SUM(Clicks) AS PaidClicks
FROM yahoo
WHERE Date BETWEEN '2018-05-06' AND '2018-05-07'
GROUP BY CampaignName) AS yaho
ON validclick.CampaignName = yaho.CampaignName
LEFT JOIN
(SELECT CampaignName,
SUM(Cost) AS Spend,
SUM(Clicks) AS PaidClicks
FROM adwords
WHERE Date BETWEEN '2018-05-06' AND '2018-05-07'
GROUP BY CampaignName) AS google
ON validclick.CampaignName = google.CampaignName
LEFT JOIN
(SELECT camp.CampaignName AS CampaignName,
SUM(vc.Impressions) AS Impressions
FROM
(SELECT AffID,
MAX(CampaignName) AS CampaignName
FROM campaigns
GROUP BY AffID) AS camp
JOIN
(SELECT ty AS AffID,
COUNT(DISTINCT(id)) AS Impressions
FROM validclickimpressions
WHERE ts BETWEEN '2018-05-06 00:00' AND '2018-05-07 23:59'
GROUP BY AffID) AS vc
ON vc.AffID = camp.AffID
GROUP BY camp.CampaignName) AS vci
ON validclick.CampaignName = vci.CampaignName
ORDER BY CampaignName;
I'm aware this may not be the most efficient MySQL statement, but we will soon be changing the structure of things so i's not a big deal. For now I need some way to use OUTER join, or do a LEFT JOIN UNTION RIGHT JOIN but with an alias. The tables (aliases) I need to full join are vci, facebook, google, and yaho. Any ideas on how to tackle this?
MySQL does not support FULL [OUTER] JOIN.
We can emulate a full outer join in MySQL using two separate select, combining the results. The pattern of an outer join and an anti-join.
-- outer join (all rows from a along with matching rows from b)
SELECT ... FROM a LEFT JOIN b ON ...
UNION ALL
-- anti-join (rows from b with no matching row in a)
SELECT ... FROM b LEFT JOIN a ON ... WHERE a.notnull_col IS NULL
As a simplistic demonstration, two tables a and b:
table a table b
an bn
------- -------
1 2
2 3
3 5
4 7
Example query
-- left outer join (rows in a with matching rows from b)
SELECT a.an, b.bn
FROM a
LEFT
JOIN b
ON b.bn = a.an
UNION ALL
-- anti-join (rows from b with no match in a)
SELECT a.an, b.bn
FROM b
LEFT
JOIN a
ON a.an = b.bn
WHERE a.an IS NULL
should return something like this (without ORDER BY clause, order of rows is indeterminate)
an bn
------- -------
1 (NULL)
2 2
3 3
4 (NULL)
(NULL) 5
(NULL) 7

Mysql query from table 2 using value from table 1

I want to search both table with all the records for cid 23 here
Total is table1-cid:23&w_id:1+2->(500+300),
Advance is table1-cid:23&w_id:1+2(100+100)+table 2-w_id:1+2(100+100+100+150)
Pending is Total-Advance
Tried using below query to display last table in pic with no luck.
SELECT E.cid, SUM(E.total) as Total, SUM(E.advance)as Advance, (SUM(E.total)-SUM(E.advance)- SUM(R.advance)) as Pending
FROM table1 AS E
LEFT JOIN table2 R ON E.w_id=R.w_id
WHERE (E.cid =23)
This is not the best query I've done but I obtain the result you want:
wwtest1 = table-1 , wwtest2 = table 2.
SELECT w1.cid AS cid,
(SELECT SUM(total) FROM wwtest WHERE cid = 23) AS total,
((SELECT SUM(advance) FROM wwtest WHERE cid = 23) + (SELECT SUM(advance) FROM wwtest2)) AS advance,
((SELECT SUM(total) FROM wwtest WHERE cid = 23) - ((SELECT SUM(advance) FROM wwtest WHERE cid = 23) + (SELECT SUM(advance) FROM wwtest2))) AS pending
FROM wwtest w1
WHERE w1.cid = 23 GROUP BY w1.cid;

mysql need to extract median value from query

I have the following query from which I need to extract the median value of total_views.
SELECT
#rownum:=#rownum + 1 AS row_num, total_views, projectId
FROM
(SELECT
a.creation,
a.projectId,
devices,
browserIds,
devices + browserIds AS total_views
FROM
((SELECT
projectId, creation
FROM
event
WHERE
kind = 'project_creation'
AND creation > '2017-04-28') a
INNER JOIN ((SELECT
COUNT(DISTINCT deviceId) AS devices, projectId, creation
FROM
event
WHERE
kind = 'open' AND component = 'mobile'
GROUP BY projectId) b
JOIN (SELECT
COUNT(DISTINCT browserId) AS browserIds, projectId, creation
FROM
event
WHERE
kind = 'open' AND component = 'web'
GROUP BY projectId) c ON b.projectId = c.projectId) ON a.projectId = b.projectId
OR a.projectId = c.projectId)
ORDER BY total_views ASC) d,
(SELECT #rownum:=0) e
;
This a part of the result :
1 1 151
2 1 256
3 1 301
4 2 404
5 2 305
6 3 895
7 4 654
8 4 369
9 9 874
10 10 123
I need to extend the query to extract the median value of total_views.
Any ideas?
Found the solution, needed to use the value of the #rownum variable instead of using the value of the field row_num to determine the position of the middle value.
I then calculate the average value of the total_views in the middle of the result set.
(Average of two middle values if the result has an even number of lines. average of the middle value if the resultset has an odd number of lines, which is the same as the middle value).
thus using the condition :
WHERE row_num in (CEIL(#rownum/2), FLOOR(#rownum/2))
full query:
SELECT avg(total_views) from
(SELECT
#rownum:=#rownum + 1 AS row_num, total_views, projectId
FROM
(SELECT
a.creation,
a.projectId,
devices,
browserIds,
devices + browserIds AS total_views
FROM
((SELECT
projectId, creation
FROM
event
WHERE
kind = 'project_creation'
AND creation > '2017-04-28') a
INNER JOIN ((SELECT
COUNT(DISTINCT deviceId) AS devices, projectId, creation
FROM
event
WHERE
kind = 'open' AND component = 'mobile'
GROUP BY projectId) b
JOIN (SELECT
COUNT(DISTINCT browserId) AS browserIds, projectId, creation
FROM
event
WHERE
kind = 'open' AND component = 'web'
GROUP BY projectId) c ON b.projectId = c.projectId) ON a.projectId = b.projectId
OR a.projectId = c.projectId)
ORDER BY total_views ASC) d,
(SELECT #rownum:=0) e) f WHERE row_num in (CEIL(#rownum/2), FLOOR(#rownum/2))
;

Sql server errors in query

I am trying to collaborate 3 queries to perform arithmetic operation. The queries are shown in
(SELECT ITEM_ID,ISNULL(SUM(REC_GOOD_QTY),0)
FROM INVENTORY_ITEM
WHERE COMPANY_ID = 1
AND INVENTORY_ITEM.COMPANY_BRANCH_ID = 1
AND INVENTORY_ITEM.INV_ITEM_STATUS = 'Inward'
AND GRN_DATE < CAST('2017-01-10 00:00:00.0' AS DATETIME)
GROUP BY INVENTORY_ITEM.ITEM_ID) -
(SELECT ITEM_ID, SUM ( TOTAL_LITRE )
FROM STOCK_REQUISITION_ITEM B, STOCK_REQUISITION A
WHERE A.ID = B.REQUISITION_ID
AND A.COMPANY_ID = 1
AND A.REQ_FROM_BRANCH_ID = 1
AND A.REQUISITION_DATE < CAST('2017-01-10 00:00:00.0' AS DATETIME)
GROUP BY B.ITEM_ID) +
(SELECT ITEM_ID, SUM ( RETURN_QUANTITY )
FROM STOCK_RETURN_ITEM B, STOCK_RETURN A
WHERE A.ID = B.STOCK_RETURN_ID
AND A.COMPANY_ID = 1
AND A.COMPANY_BRANCH_ID = 1
AND A.RETURN_DATE <= CAST('2017-01-10 00:00:00.0' AS DATETIME)
GROUP BY B.ITEM_ID)
I am getting this error.
[Err] 42000 - [SQL Server]Incorrect syntax near '-'.
42000 - [SQL Server]Incorrect syntax near '+'
Not much to go on here for details. And we aren't actually sure if you are using mysql or sql server but pretty sure you are using sql server. I think you can accomplish what you are trying to do with something along these lines.
with Iventory as
(
SELECT i.ITEM_ID
, GoodQty = ISNULL(SUM(i.REC_GOOD_QTY), 0)
FROM INVENTORY_ITEM i
WHERE COMPANY_ID = 1
AND i.COMPANY_BRANCH_ID = 1
AND i.INV_ITEM_STATUS = 'Inward'
AND i.GRN_DATE < '2017-01-10'
GROUP BY i.ITEM_ID
)
, StockRequisition as
(
SELECT ITEM_ID
, TotalLitre = SUM(TOTAL_LITRE)
FROM STOCK_REQUISITION_ITEM B
JOIN STOCK_REQUISITION A ON A.ID = B.REQUISITION_ID
WHERE A.COMPANY_ID = 1
AND A.REQ_FROM_BRANCH_ID = 1
AND A.REQUISITION_DATE < '2017-01-10'
GROUP BY B.ITEM_ID
)
StockReturn as
(
SELECT ITEM_ID
, ReturnQuantity = SUM(RETURN_QUANTITY)
FROM STOCK_RETURN_ITEM B
JOIN STOCK_RETURN A ON A.ID = B.STOCK_RETURN_ID
WHERE A.COMPANY_ID = 1
AND A.COMPANY_BRANCH_ID = 1
AND A.RETURN_DATE <= '2017-01-10'
GROUP BY B.ITEM_ID
)
select i.ITEM_ID
, MyCalculation = i.GoodQty - isnull(Req.TotalLitre, 0) + isnull(sr.ReturnQuantity, 0)
from Inventory i
left join StockRequisition sr on sr.ITEM_ID = i.ITEM_ID
left join StockReturn Req on Req.ITEM_ID = i.ITEM_ID
In your queries you always returns two fields ITEM_ID and a numeric field.
To apply an arithmetical operation you must return one numeric field
The first query:
SELECT ITEM_ID,ISNULL(SUM(REC_GOOD_QTY),0)
becomes
SELECT ISNULL(SUM(REC_GOOD_QTY),0)
The second query:
SELECT ITEM_ID, SUM ( TOTAL_LITRE )
becomes
SELECT SUM ( TOTAL_LITRE )
The third query:
SELECT ITEM_ID, SUM ( RETURN_QUANTITY )
becomes
SELECT SUM ( RETURN_QUANTITY )
So the GROUP BY returns more than one row per query
UPDATE
i try to rewrite your query:
SELECT DISTINCT ii.item_id,
ISNULL(
(SELECT SUM(ii2.rec_good_qty)
FROM inventory_item ii2
WHERE ii2.item_id = ii.item_id
AND ii.company_id = 1
AND ii.company_branch_id = 1
AND ii.inv_item_status = 'Inward'
AND ii.grn_date < CAST('2017-01-10 00:00:00.0' AS DATETIME))
,0) -
ISNULL(
(SELECT SUM(total_litre)
FROM stock_requisition_item b
JOIN stock_requisition a
ON a.id = b.requisition_id
WHERE a.company_id = 1
AND a.req_from_branch_id = 1
AND a.requisition_date < CAST('2017-01-10 00:00:00.0' AS DATETIME))
,0) +
ISNULL(
(SELECT SUM(return_quantity)
FROM stock_return_item b
JOIN stock_return a
ON a.id = b.stock_return_id
WHERE a.company_id = 1
AND a.company_branch_id = 1
AND a.return_date <= CAST('2017-01-10 00:00:00.0' AS DATETIME))
,0) AS result
FROM inventory_item ii
WHERE ii.company_id = 1
AND ii.company_branch_id = 1
AND ii.inv_item_status = 'Inward'
AND ii.grn_date < CAST('2017-01-10 00:00:00.0' AS DATETIME)