Merging Data to single query - sql

I have two queries one is to get ISSUE and RETURN of Items from table.
select MATU.ITEMNUM ,
MATU.DESCRIPTION ,
MATU.STORELOC ,
MATU.CONDITIONCODE,
MATU.ISSUETYPE,
SUM(MATU.QUANTITY )as QUANTITY,
INV.MINLEVEL,
INV.MAXLEVEL
from MATUSETRANS MATU
LEFT OUTER JOIN Inventory INV
ON INV.ITEMNUM=MATU.ITEMNUM
AND INV.LOCATION=MATU.STORELOC
where MATU.ITEMNUM='H95-04-0010' --A57-01-0459A
AND MATU.TRANSDATE >'01-JAN-19'
AND MATU.CONDITIONCODE='01' and MATU.STORELOC='09'
GROUP BY MATU.ITEMNUM ,MATU.DESCRIPTION ,MATU.STORELOC ,INV.MINLEVEL,INV.MAXLEVEL,MATU.PONUM ,MATU.ISSUETYPE,MATU.CONDITIONCODE;
Which result look like
And My second query is get TRANSFER IN and TRANSFER OUT Items from table
select ITEMNUM ,
DESCRIPTION,
TOSTORELOC ,
FROMSTORELOC ,
--TRANSDATE ,
sum(QUANTITY) as QUANTITY ,
ISSUE_CATEGORY as ISSUETYPE,LOCATION from
(select MATR.ITEMNUM,MATR.DESCRIPTION,MATR.TOSTORELOC,MATR.FROMSTORELOC,MATR.TRANSDATE,MATR.QUANTITY,MATR.ISSUETYPE,
CASE WHEN INV.LOCATION = MATR.FROMSTORELOC THEN 'TRANSFER OUT'
WHEN INV.LOCATION = MATR.TOSTORELOC THEN 'TRANSFER IN'
ELSE '_'END as ISSUE_CATEGORY,
MATR.DOCNUM,INV.LOCATION
from MATRECTRANS MATR
INNER JOIN INVENTORY INV
ON INV.ITEMNUM=MATR.ITEMNUM
where MATR.Itemnum='H95-04-0010' AND MATR.TRANSDATE>'01-JAN-19')
where ISSUE_CATEGORY in ('TRANSFER IN','TRANSFER OUT') and DOCNUM is not null and location='09'
group by ITEMNUM,DESCRIPTION ,TOSTORELOC ,FROMSTORELOC ,ISSUETYPE ,ISSUE_CATEGORY,LOCATION;
Which result look like
When I am trying to join both record look like, record are repeating!
How can i tackle this issue?
I need like this
If theres any TRANSFER IN/OUT values then show them else 0.

Related

I want to show only the latest SQL Query

I have some issues with duplicate SQL tables. When I run the query, I am looking to show the MOST recent “Order ID.” When I run the program, it will show me every single order ID from the company. I only want to pull the latest order ID. Is there something wrong with my query? Is there something I can add or remove?
I want to see the latest order number, currently I see them all.
SELECT DISTINCT
payee.id AS 'Carrier ID'
, payee.status AS 'Status'
, CASE
WHEN payee.status = 'I' THEN 0
WHEN payee.status = 'A' THEN 100
ELSE 0
END AS 'Active %'
, drs_payee.icc_number AS 'MC #'
, payee.name AS 'Name'
, CAST(drs_payee.liab_expire_date AS DATE) AS 'Liab Date'
, CAST(drs.payee.cargo_ins_renew_dt AS DATE) AS 'Cargo Date'
, CONCAT(contact.email,'; ' ,drs_payee.ins_expire_notify) AS 'Emails'
, orders.id AS 'Order ID'
--, CAST(stop.sched_arrive_early AS DATE) AS 'Delivery Date'
FROM payee
LEFT JOIN drs_payee ON payee.id = drs_payee.id
INNER JOIN contact ON payee.id = contact.parent_row_id
LEFT JOIN movement ON payee.id = movement.override_payee_id
LEFT JOIN orders ON orders.curr_movement_id = movement.id
LEFT JOIN stop ON movement.dest_stop_id = stop.sched_arrive_early
WHERE contact.sequence = '1'
Try to use ORDER BY [column_name] desc along with query and LIMIT if required.

Grouping Multiple Rows into one Row

Here its my script to read stores QTY depending on ITEM SID, I need to group all records which are related to same ITEM SID to be merged together in one line, find below example images for result and expected results.
SELECT DISTINCT
i.SBS_NO,
to_char(i.ITEM_SID) as ITEMSID,
i.ALU ,
a.LOT_NUMBER ,
a.LOT_NAME,
a.LOT_NOTE,
a.EXPIRY_DATE,
a.ACTIVE ,
--s.STORE_NO,
--s.QTY,
DECODE(S.STORE_NO,1,S.QTY,'0') STR1QTY,
DECODE(S.STORE_NO,2,S.QTY,'0') STR2QTY,
DECODE(S.STORE_NO,3,S.QTY,'0') STR3QTY,
DECODE(S.STORE_NO,4,S.QTY,'0') STR4QTY,
DECODE(S.STORE_NO,5,S.QTY,'0') STR5QTY,
DECODE(S.STORE_NO,6,S.QTY,'0') STR6QTY,
DECODE(S.STORE_NO,7,S.QTY,'0') STR7QTY,
DECODE(S.STORE_NO,0,S.QTY,'0') STR0QTY,
DECODE(S.STORE_NO,99,S.QTY,'0') WHQTY,
i.DESCRIPTION2,
i.DESCRIPTION3,
i.DESCRIPTION4,
i.DCS_CODE,
i.ATTR,
i.SIZ,
i.FST_RCVD_DATE,
i.UDF1_DATE,
i.QTY_PER_CASE,
i.ACTIVE,
i.MARKDOWN_PRICE,
i.UDF2_VALUE as ITEM_STATUS
from inventory_v i
inner join LOT a
on i.ITEM_SID = a.ITEM_SID
inner join LOT_QTY s
on a.ITEM_SID=s.ITEM_SID
where i.sbs_no=1
and i.ITEM_SID=a.ITEM_SID
--and i. ALU='358N690175'
and a.ITEM_SID=s.ITEM_SID
and i.SBS_NO=a.SBS_NO
and a.SBS_NO=s.SBS_NO
and s.STORE_No in (0,1,2,3,4,5,6,7,99)
and a.ACTIVE=1
and i.ACTIVE=1
GROUP BY
i.SBS_NO,
i.ITEM_SID,
i.ALU ,
a.LOT_NUMBER ,
a.LOT_NAME,
a.LOT_NOTE,
a.EXPIRY_DATE,
a.ACTIVE ,
s.STORE_NO,
s.QTY,
i.DESCRIPTION2,
i.DESCRIPTION3,
i.DESCRIPTION4,
i.DCS_CODE,
i.ATTR,
i.SIZ,
i.FST_RCVD_DATE,
i.UDF1_DATE,
i.QTY_PER_CASE,
i.ACTIVE,
i.MARKDOWN_PRICE,
i.UDF2_VALUE
;
THANKS
[here the current result ]
[expected result]

SQL - Summarizing Monthly Sales Data

I have two tables that I need to combine, but I can't get to seem the joins to work. The picture has three tables
_date_array2: Has a field DateMonthYr that contains all possible date/yr combinations
_sales_summ_tbl__ => Has 5 fields. Only months with sales show up. For example, you see only three records showing up for the second table. There is no 5/2016, for example, because there were no sales for that month.
My goal is to "pad" the second table to have TotalDemand of 0's for months with no sales. I am very close (see the third table), except I cannot get the PartNumber to show up for dates with no sales.
My guess is that it's due to the RIGHT JOIN. But I'm not sure how to handle this. The output I am hoping for is table 3 but with the part number populated for all entries.
And here is my code (the results from running this code are the third/last table in the picture):
SELECT TmpSalesTbl.PartNumber as PartNumber,
tmp_date_array.CreateDateMonth as CreateDateMonth,
tmp_date_array.CreateDateYear as CreateDateYear,
CASE WHEN TmpSalesTbl.TotalDemand is NULL THEN 0 ELSE TmpSalesTbl.TotalDemand END as TotalDemand
FROM #_sales_summ_tbl__ TmpSalesTbl
RIGHT JOIN #_date_array2 tmp_date_array on tmp_date_array.CreateDateMonthYr = TmpSalesTbl.CreateDateMonthYr
ORDER BY tmp_date_array.CreateDateYear, tmp_date_array.CreateDateMonth
It is more conventional to place the list of all dates first, then left join to the data and whilst using a case expression is fine an alternative is coalesce(). This should ensure all the wanted months/years display:
SELECT
tmpsalestbl.PartNumber AS partnumber
, tmp_date_array.CreateDateMonth AS createdatemonth
, tmp_date_array.CreateDateYear AS createdateyear
, COALESCE(tmpsalestbl.TotalDemand, 0) AS totaldemand
FROM #_date_array2 tmp_date_array
LEFT JOIN #_sales_summ_tbl__ tmpsalestbl ON tmp_date_array.CreateDateMonthYr = tmpsalestbl.CreateDateMonthYr
ORDER BY
tmp_date_array.CreateDateYear
, tmp_date_array.CreateDateMonth
To populate for evey partnumber, on every month, you will need a new subquery:
select distinct PartNumber #_sales_summ_tbl__
And then cross join that to the years/months so you have a complete set of years/months/parts.
SELECT
cj.PartNumber AS partnumber
, tmp_date_array.CreateDateMonth AS createdatemonth
, tmp_date_array.CreateDateYear AS createdateyear
, COALESCE(tmpsalestbl.TotalDemand, 0) AS totaldemand
FROM #_date_array2 tmp_date_array
CROSS JOIN (
SELECT DISTINCT
PartNumber FROM #_sales_summ_tbl__
) cj
LEFT JOIN #_sales_summ_tbl__ tmpsalestbl ON tmp_date_array.CreateDateMonthYr = tmpsalestbl.CreateDateMonthYr
AND cj.PartNumber = tmpsalestbl.PartNumber
ORDER BY
tmp_date_array.CreateDateYear
, tmp_date_array.CreateDateMonth
;

SQL - Only show results for one column in first instance of a duplicated record

I am finding it difficult to explain exactly what I am trying to achieve so I think it best to show a visual representation.
Example of how my query results currently look
Example of how I want the results to look
The report I am running shows a list of every product within orders. Each product has its own cost assigned to it. Another column is a delivery charge, but this is a charge assigned to the order; not individual products. I want to be able to show the delivery charge against the first product in each order ONLY.
I have attempted, for far too long, to try and find an answer to this query but have had no luck. I don't know if it is even possible so assistance of any sort, or even just being pointed in the right direction, would be of great help.
Thanks
EDIT.
If it helps here is my query:
SELECT dbo.Orders.EncryptedOrderId,
dbo.OrderProduct.ProductID,
dbo.OrderProduct.QuantityPerRecipient,
dbo.OrderProduct.NumRecipients,
dbo.OrderProduct.TotalQuantity,
dbo.DocType.Name AS [Product Type],
dbo.ProductGroup_Culture.Name AS [Product Group],
RIGHT(CatalogNo, CHARINDEX('_', REVERSE('_' + CatalogNo)) -1) AS [HamptonsType],
FORMAT(dbo.Orders.DateOrderCreated, 'dd/MM/yyyy HH:mm:ss') AS 'DateOrderCreated',
CAST(REPLACE(dbo.Orders.ClearingResult, 'utf-8', 'utf-16') AS XML ).value('(/UserData//CostCenter/node())[1]', 'nvarchar(max)') AS [Cost Center],
dbo.Users.FirstName,
dbo.Users.LastName,
dbo.Users.CompanyName AS [Branch Name],
dbo.Users.Department AS Subsidiary,
dbo.Users.Custom1,
dbo.Users.Custom2,
dbo.Users.Custom3,
dbo.Users.Custom4,
dbo.Users.Custom5,
dbo.OrderProduct.TotalPrice,
dbo.Orders.ShippingCharges,
dbo.OrderProduct.OrderProductID,
dbo.FileSubmissionDocument.OriginalFileType,
COALESCE (dbo.FileSubmissionDocument.Title, dbo.Product_Culture.Name) AS [Product Name],
OPDV.FriendlyValue AS 'BCard Recipient'
FROM dbo.DocType
INNER JOIN dbo.Doc
ON dbo.DocType.DocTypeID = dbo.Doc.DocTypeID
INNER JOIN dbo.OrderProduct
ON dbo.Doc.ProductID = dbo.OrderProduct.ProductID
LEFT JOIN dbo.Product
ON dbo.Product.ProductID = dbo.Doc.ProductID
LEFT JOIN dbo.ProductGroupMembership
ON dbo.ProductGroupMembership.ProductID = dbo.Doc.ProductID
LEFT JOIN dbo.ProductGroup_Culture
ON dbo.ProductGroup_Culture.ProductGroupID = dbo.ProductGroupMembership.ProductGroupID
INNER JOIN dbo.Orders
ON dbo.OrderProduct.OrderID = dbo.Orders.OrderID
INNER JOIN dbo.Users
ON dbo.Orders.UserID = dbo.Users.UserID
INNER JOIN dbo.Product_Culture
ON dbo.OrderProduct.ProductID = dbo.Product_Culture.ProductID
INNER JOIN dbo.Store_Culture
ON dbo.Store_Culture.StoreID = dbo.Users.AssignedToStoreID FULL OUTER
JOIN dbo.FileSubmissionDocument
ON dbo.OrderProduct.OrderProductID = dbo.FileSubmissionDocument.SubOrderProductID - 1
LEFT JOIN (SELECT OP.OrderProductID,
OP.DialID,
OP.FriendlyValue
FROM OrderProductDialValue OP
LEFT JOIN Dial DI ON DI.DialID = OP.DialID
LEFT JOIN OrderProduct OT ON OT.OrderProductID = OP.OrderProductID
LEFT JOIN Product PR ON PR.ProductID = OT.ProductID
WHERE PR.ExternalID = 'BCName'
AND DI.UProduceDialName = 'Name') OPDV ON OPDV.OrderProductID = dbo.OrderProduct.OrderProductID
WHERE ('#CUSTOMERNAME' is null
OR '#CUSTOMERNAME' = ''
OR dbo.Store_Culture.Name LIKE '%' + '#CUSTOMERNAME' + '%')
AND dbo.OrderProduct.IsDraft = 0
AND dbo.Orders.IsCart=0
AND dbo.Orders.IsSaveForLater=0
AND (('#DATE' <= dbo.Orders.DateOrderCreated)
OR ('#DATE' IS NULL)
OR ('#DATE'=''))
AND ((DATEADD(day, 1, '#DATE') >= dbo.Orders.DateOrderCreated)
OR ('#DATE' IS NULL)
OR ('#DATE'=''))
AND dbo.Users.LastName NOT LIKE '%TEST%'
ORDER BY dbo.Orders.OrderID DESC, dbo.OrderProduct.OrderProductID DESC
The query runs through a reporting system on an online portal so the values that show as #CUSTOMERNAME or #DATE are variables based on values given at the time when the report is run.
this may help you
select orderid,
productid,
productvalue,
case ROW_NUMBER() over (partition by orderid order by orderid)
when 1 then deliverycharge
else null end as 'deliverycharge'
from ........
I assume your query looks like
select orderID
, productID
, productValue
, DeliveryCharge
from test_t
order by orderID
, productValue desc
;
and that you want delivery charges listed for the most expensive product of each order.
If supported by your rdbms, you can use the analytic RANK function
select orderID
, productID
, productValue
, DeliveryCharge
, CASE RANK() OVER ( PARTITION BY orderID ORDER BY productValue DESC ) WHEN 1 THEN DeliveryCharge ELSE NULL END r
from test_t
order by orderID
, productValue desc
;
If your rdbms does not support RANK, you can emulate it using a left join with a suitably aggregated copy of your table:
select t.orderID
, t.productID
, t.productValue
, rt.mdc DeliveryCharge
from test_t t
left join (
select orderID
, max(productValue) mp
, max(DeliveryCharge) mdc
from test_t
group by orderID
) rt
on (
rt.orderID = t.orderID
AND rt.mp = t.productValue
)
order by orderID
, productValue desc
;
The tacit assumption is that the delivery charge is by order (which seems reasonable as you wouldn't want to selectively drop it otherwise, right ?).
Moreover, both solutions will produce multiple rows containing the delivery charge per order if that order contains multipleproducts with the same productValue.
Tested on oracle 12c1;

Exclude few selected fields on group by

I had a query that was returning member transaction information. This query has an aggregate function to calculate the amount. All is working fine according to its grouping. Now what I need to do is to add two more columns from different tables. I did try to add them unfortunately they are giving me duplicated information with tons number of records.
Can anyone help me I just want to be able to include the two fields on the query and not include them in the group by clause. And also ensure that data returned is not a duplicate
See below is the query I used.
DECLARE #LastMonthExtractID Int = 11
SELECT x.*
,lstmnth.Submission ---added
,lm_subt.SubmissionTypeDescription ---added
FROM (
SELECT MemberRef --unique key
, SiteName
, ChargePeriod
, SUM(Amount) AS Amount
, TransactionMap
, PackageCode
FROM (
SELECT MemberRef
, SiteName
, ChargePeriod
, Amount
, PackageCode
, CASE WHEN map.TransactionMap = 'JoinFee' AND lstmnth.ChargeDate <> lstmnth.JoinDate THEN 'PayPlan'
WHEN map.TransactionMap = 'MemberFee' AND lstmnth.PackageCode LIKE 'PV%' AND lstmnth.SiteID <> 15 THEN 'VitalityMF' -- must use Package and not CURRENT PACKAGE
WHEN map.TransactionMap = 'MemberFee' AND lstmnth.PackageCode LIKE 'PV%' AND lstmnth.SiteID = 15 THEN 'PlatVitalityMF' -- PLATINUM
WHEN map.TransactionMap = 'MemberFee' AND lstmnth.PackageCode LIKE 'Z%' THEN 'ZContract'
WHEN map.TransactionMap IS NULL THEN 'Other'
ELSE map.TransactionMap END AS TransactionMap
--, lstmnth.Submission
--, lm_subt.SubmissionTypeDescription --added
FROM dbo.CCX_Billing lstmnth
LEFT JOIN dbo.TransactionMap map on lstmnth.TransactionType = map.TransactionType
AND lstmnth.TransactionDescription = map.TransactionDescription
AND ISNULL (lstmnth.AnalysisCode, '') = map.AnalysisCode
WHERE lstmnth.ExtractID = #LastMonthExtractID
) l
GROUP BY SiteName, MemberRef, ChargePeriod, PackageCode, TransactionMap
) x
INNER JOIN dbo.CCX_Billing lstmnth ON lstmnth.MemberRef = x.MemberRef
LEFT JOIN dbo.CCX_Billing_PSubmission lm_sub on lstmnth.SubmissionID = lm_sub.ID
INNER JOIN dbo.CCX_Billing_SubmissionType lm_subt on lm_sub.SubmissionTypeID = lm_subt.SubmissionID --added