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.
Related
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.
I am looking to create a query that shows shipping number, the container ID, the tracking number, the location it was last moved to, what time it was moved, and who moved it.
Here's the issue. We recently backed up or transaction history onto another table for anything that's over 30 days old.
So I have the table transaction_history which gives me everything from today to 30 days ago, and I have the table AR_transaction_history, which gives me everything else (starting from 31 days ago.)
I need to be able to create prompts for the user to input either the container ID, tracking number, or shipping ID.
I need help joining the two tables to create 1 table with all the records. I tried union all and it does not work with my prompts. I tried an isnull statement and that didn't work either. Here is the code.
select
th.reference_id,
th.container_id 'Container ID',
sc.tracking_number 'Tracking Number',
max(th.DATE_TIME_STAMP) 'Time of Last Touch',
CASE
WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.user_name
END AS 'User Name',
CASE
WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.location
END AS 'Location'
from TRANSACTION_HISTORY th
inner join TRANSACTION_HISTORY th1 on th1.CONTAINER_ID = th.CONTAINER_ID
inner join SHIPPING_CONTAINER sc on sc.CONTAINER_ID = th.CONTAINER_ID
group by th.container_id, sc.tracking_number, th1.DATE_TIME_STAMP, th1.USER_NAME, th1.LOCATION, th.REFERENCE_ID
Having
CASE
WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.user_name
END is not null
UNION ALL
select
th.reference_id,
th.container_id 'Container ID',
sc.tracking_number 'Tracking Number',
max(th.DATE_TIME_STAMP) 'Time of Last Touch',
CASE
WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.user_name
END AS 'User Name',
CASE
WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.location
END AS 'Location'
from AR_TRANSACTION_HISTORY th
inner join AR_TRANSACTION_HISTORY th1 on th1.CONTAINER_ID = th.CONTAINER_ID
inner join AR_SHIPPING_CONTAINER sc on sc.CONTAINER_ID = th.CONTAINER_ID
group by th.container_id, sc.tracking_number, th1.DATE_TIME_STAMP, th1.USER_NAME, th1.LOCATION, th.REFERENCE_ID
Having
CASE
WHEN th1.date_time_stamp = max(th.DATE_TIME_STAMP) then th1.user_name
END is not null
Do UNION ALL in a subquery, and leave the rest of your original query untouched. This is the simplest way to proceed, without reviewing the whole logic of your (aggregated) query.
SELECT
....
FROM
(
SELECT * FROM TRANSACTION_HISTORY
UNION ALL SELECT * FROM AR_TRANSACTION_HISTORY
) as th
INNER JOIN SHIPPING_CONTAINER sc on sc.CONTAINER_ID = th.CONTAINER_ID
GROUP BY ...
Note: in general, SELECT * and UNION ALL do not get along well. This answer assumes that tables TRANSACTION_HISTORY and AR_TRANSACTION_HISTORY have exactly the same structure (columns and data types).
I have a SQL query i'm currently working on which i would greatly appreciate some help with.
Here is a simplified version of the view I've been given to work on:
SELECT a.Organisation_Name
,a.Org_Id
,b.Activity_month
,SUM(b.Activity_Plan) 'Plan_Activity'
,SUM(b.Activity_Actual) 'Actual_Activity'
,SUM(b.Price_Actual) 'Actual_Price'
,SUM(b.Price_Plan) 'Plan_Price'
,COUNT(b.Instances) AS 'Record_Count'
,CASE WHEN COUNT(b.Instances) > 0 THEN 'Yes' ELSE 'No' END AS Submitted
FROM [ExampleDatabase].[dbo].[Organisation_Reference] a
LEFT JOIN [ExampleDatabase].[dbo].[Report_Submissions] b
ON a.Org_Id = b.Org_Id
AND ([Exmaple_Code] LIKE ('X') or [Example_Code] = 'X')
WHERE a.Category_Flag = 1
AND a.Example_Code in ('X','X','X','X','X')
GROUP BY
a.Organisation_Name
,a.Org_Id
,b.Activity_month
--
The Activity Month field is an Integer rather than a date, currently ranging from 1-8.
The problem i am facing is that within the [Report_Submissions] table, it only contains organisations which have actually submitted the reports, whereas the
[Organisation_Reference] table lists all the organisations which should be submitting.
Where the organisations have submitted the reports, the data is perfect and gives me a run down of all the details i need for each individual month.
Obviously if an organisation hasn't submitted then this detail wouldn't be available, but i do need to have a complete list of all organisations listed from the reference table for each individual month and whether they have submitted the reports or not.
At the moment where the 'Submitted' field = 'No' it's only bringing back one record for each organisation that has never submitted (With Activity_month coming through as null) and if an organisation has only submitted once or twice then it will include those submissions but still be missing the rest of the months from the result set.
I've tried various different joins etc. but I seem to be drawing a blank for a solution. Is there a way of generating this information within the script? Any advice would be great!
Kind Regards,
Mark
Since you just need numbers 1-8, using a subquery in your join to cross apply(values ()) to your Organisation_Reference table works well and does not make the query much more compliCated to read.
select
a.Organisation_Name
, a.Org_Id
, a.Activity_Month
, sum(b.Activity_Plan) 'Plan_Activity'
, sum(b.Activity_Actual) 'Actual_Activity'
, sum(b.Price_Actual) 'Actual_Price'
, sum(b.Price_Plan) 'Plan_Price'
, count(b.Instances) as 'record_count'
, case when count(b.Instances) > 0 then 'yes' else 'no' end as Submitted
from (
select o.*, t.Activity_Month
from [ExampleDatabase].[dbo].[Organisation_Reference] as o
cross apply (values (1),(2),(3),(4),(5),(6),(7),(8)) t(Activity_Month)
) as a
left join [ExampleDatabase].[dbo].[Report_Submissions] b
on a.Org_Id = b.Org_Id
and a.Activity_Month = b.Activity_Month
and ([exmaple_Code] like ('X') or [Example_Code] = 'X')
where a.Category_Flag = 1
and a.Example_Code in ('X','X','X','X','X')
group by
a.Organisation_Name
, a.Org_Id
, b.Activity_Month
You could also cross join with a numbers/tally table, or use a common table expression to generate the range of numbers you need. I would recommend either of those options as well, especially if your logic was more compliCated.
If Report_Submissions contains all of the months you want in your query, you could cross join the distinct Activity_Months from that table to your Organisation_Reference table.
select
a.Organisation_Name
, a.Org_Id
, a.Activity_Month
, sum(b.Activity_Plan) 'Plan_Activity'
, sum(b.Activity_Actual) 'Actual_Activity'
, sum(b.Price_Actual) 'Actual_Price'
, sum(b.Price_Plan) 'Plan_Price'
, count(b.Instances) as 'record_count'
, case when count(b.Instances) > 0 then 'yes' else 'no' end as Submitted
from (
select o.*, t.Activity_Month
from [ExampleDatabase].[dbo].[Organisation_Reference] as o
cross join (select distinct Activity_Month from Report_Submissions) t
) as a
left join [ExampleDatabase].[dbo].[Report_Submissions] b
on a.Org_Id = b.Org_Id
and a.Activity_Month = b.Activity_Month
and ([exmaple_Code] like ('X') or [Example_Code] = 'X')
where a.Category_Flag = 1
and a.Example_Code in ('X','X','X','X','X')
group by
a.Organisation_Name
, a.Org_Id
, b.Activity_Month
I have the following query that works fine if I DON'T set a destination table.
SELECT soi.customer_id
, p.department
, p.category
, p.subcategory
, p.tier1
, p.tier2
, pc.bucket as categorization
, SUM(soi.price) as demand
, COUNT(1) as cnt
FROM store.sales_item soi
INNER JOIN datamart.product p ON (soi.product_id = p.product_id)
INNER JOIN daily_customer_fact.dcf_product_categorization pc
ON (p.department = pc.department
AND p.category = pc.category
AND p.subcategory = pc.subcategory
AND p.tier1 = pc.tier1
AND p.tier2 = pc.tier2)
WHERE DATE(soi.created_timestamp) < current_date()
GROUP EACH BY 1,2,3,4,5,6,7 LIMIT 10
However, if I set a destination table, it fails with
Error: Ambiguous field name 'app_version' in JOIN. Please use the table qualifier before field name.
That column exists on the store.sales_item table, but I'm not selecting nor joining to that column.
I've seen this error message before, and it points to the following:
Your query job when specifying a destination table is setting flattenResults to false.
Both of the store.sales_item and datamart.product tables contain a field named "app_version".
If so, I recommend looking at this answer:
https://stackoverflow.com/a/28996481/4001094
As well as this issue report: https://code.google.com/p/google-bigquery/issues/detail?id=459
In your case, you should be able to make your query succeed by doing something like the following, using suggestion #3 from the answer linked above. I'm unable to test it as I don't have access to your source tables, but it should be close to working with flattenResults set to false.
SELECT soi_and_p.customer_id
, soi_and_p.department
, soi_and_p.category
, soi_and_p.subcategory
, soi_and_p.tier1
, soi_and_p.tier2
, pc.bucket as categorization
, SUM(soi_and_p.price) as demand
, COUNT(1) as cnt
FROM
(SELECT soi.customer_id AS customer_id
, p.department AS department
, p.subcategory AS subcategory
, p.tier1 AS tier1
, p.tier2 AS tier2
, soi.price AS price
, soi.created_timestamp AS created_timestamp
FROM store.sales_item soi
INNER JOIN datamart.product p ON (soi.product_id = p.product_id)
) as soi_and_p
INNER JOIN daily_customer_fact.dcf_product_categorization pc
ON (soi_and_p.department = pc.department
AND soi_and_p.category = pc.category
AND soi_and_p.subcategory = pc.subcategory
AND soi_and_p.tier1 = pc.tier1
AND soi_and_p.tier2 = pc.tier2)
WHERE DATE(soi_and_p.created_timestamp) < current_date()
GROUP EACH BY 1,2,3,4,5,6,7 LIMIT 10
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