How to Combine Two Columns from Two different Queries with Different Datatypes? - sql

I'm trying to ultimately get a sum of two columns. The issue is that the sum is made up from two different tables. Basically it's tbl1-col1 + tabl2-col1.
I'm attempting a UNION ALL, but the issue is that for me to pull the right data from both queries to even get the right data in the col1's, I need to SELECT different parameters for both queries.
Obviously I'm working with different datatypes and header titles, so that UNION isn't going to work the way I want it to.
-------------------------------query 1------------------------------------------------
SELECT
RECEIVABLE_LINE.AMOUNT AS Total,
RECEIVABLE_LINE.INVOICE_ID,
RECEIVABLE_LINE.LINE_NO,
RECEIVABLE_LINE.GL_ACCOUNT_ID,
RECEIVABLE.INVOICE_DATE,
RECEIVABLE.TYPE
FROM RECEIVABLE_LINE INNER JOIN RECEIVABLE ON RECEIVABLE_LINE.[INVOICE_ID] = RECEIVABLE.[INVOICE_ID]
WHERE RECEIVABLE_LINE.GL_ACCOUNT_ID LIKE '4%'
AND RECEIVABLE.INVOICE_DATE >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
AND RECEIVABLE.INVOICE_DATE < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())+1, 0)
-------------------------------query 2------------------------------------------------
SELECT
SUM(SHIPPER_LINE.USER_SHIPPED_QTY*CUST_ORDER_LINE.UNIT_PRICE) AS 'Total',
SHIPPER_LINE.USER_SHIPPED_QTY,
CUST_ORDER_LINE.UNIT_PRICE,
SHIPPER.INVOICED_DATE,
SHIPPER.SHIPPED_DATE
--SUM(isnull(CAST('Total' AS decimal),0)) as 'Total of all totals'
FROM SHIPPER_LINE INNER JOIN SHIPPER ON SHIPPER_LINE.PACKLIST_ID = SHIPPER.PACKLIST_ID
LEFT JOIN CUST_ORDER_LINE ON SHIPPER_LINE.CUST_ORDER_LINE_NO = CUST_ORDER_LINE.LINE_NO AND SHIPPER_LINE.CUST_ORDER_ID = CUST_ORDER_LINE.CUST_ORDER_ID
WHERE SHIPPER.INVOICED_DATE Is Null
AND SHIPPER.SHIPPED_DATE BETWEEN '2020-09-01' AND '2020-09-10'
GROUP BY SHIPPER_LINE.USER_SHIPPED_QTY, CUST_ORDER_LINE.UNIT_PRICE, SHIPPER.INVOICED_DATE, SHIPPER.SHIPPED_DATE
ORDER BY SHIPPER.INVOICED_DATE
What are my options at this point?

Related

Two Table Join Into One Result

I have two tables where I am attempting to join the results into one. I am trying to get the INV_QPC which is the case pack size shown in the results (SEIITN and SKU) are the same product numbers.
The code below gives two results, but the goal is to get the bottom result into the main output, where I was hoping the join would be the lookup to show the case pack size in relation to SKU.
INV_QPC = case pack size
SKU = SKU/Product Number
SEIITN = SKU/Product Number
Thanks for looking.
SELECT
ORDER_QTY, SKU, INVOICE_NUMBER, CUSTOMER_NUMBER, ROUTE,
ALLOCATED_QTY, SHORTED_QTY, PRODUCTION_DATE,
DATEPART(wk, PRODUCTION_DATE) AS FISCAL_WEEK,
YEAR(PRODUCTION_DATE) AS FISCAL_YEAR,
CONCAT(SKU, CUSTOMER_NUMBER) AS SKU_STORE_WEEK
FROM
[database].[dbo].[ORDERS]
WHERE
[PRODUCTION_DATE] >= DATEADD(day, -3, GETDATE())
AND [PRODUCTION_DATE] <= GETDATE()
SELECT INV_QPC
FROM [database].[dbo].[PRODUCT_MASTER]
JOIN [database].[dbo].[ORDERS] ON ORDERS.SKU = PRODUCT_MASTER.SEIITN;
It looks like you are on the right track, but your second SQL statement is only returning the INV_QPC column, so it is not being joined to the first query. Here is an updated SQL statement that should give you the result you are looking for:
SELECT
ORD.ORDER_QTY, ORD.SKU, ORD.INVOICE_NUMBER, ORD.CUSTOMER_NUMBER, ORD.ROUTE,
ORD.ALLOCATED_QTY, ORD.SHORTED_QTY, ORD.PRODUCTION_DATE,
DATEPART(wk, ORD.PRODUCTION_DATE) AS FISCAL_WEEK,
YEAR(ORD.PRODUCTION_DATE) AS FISCAL_YEAR,
CONCAT(ORD.SKU, ORD.CUSTOMER_NUMBER) AS SKU_STORE_WEEK,
PROD.INV_QPC
FROM
[database].[dbo].[ORDERS] ORD
JOIN [database].[dbo].[PRODUCT_MASTER] PROD ON ORD.SKU = PROD.SEIITN
WHERE
ORD.PRODUCTION_DATE >= DATEADD(day, -3, GETDATE())
AND ORD.PRODUCTION_DATE <= GETDATE()
In this query, I have added the INV_QPC column to the SELECT statement, and also included the join condition in the JOIN clause. Additionally, I have given aliases to the tables in the FROM and JOIN clauses to make the query easier to read. Finally, I have updated the WHERE clause to reference the ORD alias instead of the table name directly.

joining three select statements

I create reports in SQL Server Report Builder. I hope anyone can help me in this case. My query shows me an error if I add a third inner join
How can I add a third select statement?
You need to update the final GROUP BY clause. Including the full name in the SELECT clause requires the full name in the GROUP BY.
As a rule of thumb: When using GROUP BY every field used in the SELECT clause, that isn't combined with an aggregate function, must appear.
Select
SUM(cast(Units as int)) as CounterName,
left(Name,4) as Machine,
Name as WasteLabel
from
Trouble
inner join tsystem ON Trouble.systemid = tsystem.id
where
Name not in ('Aus', 'An', 'Produced')
and IntervalDateWeek >= dateadd(wk, datediff(wk, 0, getdate()) - 2, 0)
and IntervalDateWeek <= dateadd(wk, datediff(wk, 0, getdate())-1, 0)
and left(Name, 4) in (Select name from tSystem
where
ID in
(
Select
systemid
from
tsystemviewSystemwhere
WHERE
SystemViewID = 4)
)
group by
Name
I suspect your query could be improved. Adding clear sample data and expected output will help here.

Combining the results of two JOINS in SQL

Tickets last 24 hours and can be either 'Child', 'Adult' or 'Teen'. Essentially, a ticket can be 'ConnectedTo' a number of movies. Child tickets for example will be connected to movies with a age rating of PG or below, while Adult tickets will be connected to every single movie.
The below returns info on all the tickets purchased for movies from the previous month:
SELECT *
FROM
[Test_DB].[dbo].[Tickets]
INNER JOIN
[Test_DB].[dbo].[Movies]
ON
[Test_DB].[dbo].[Tickets].[ConnectedTo] = [Test_DB].[dbo].[Movies].[MovieID]
WHERE
[Test_DB].[dbo].[Tickets].[DateEntered] >= DATEADD(month, DATEDIFF(month, 0, GETDATE())-1, 0) AND [Test_DB].[dbo].[Tickets].[DateEntered] <= DATEADD(month, DATEDIFF(month, 0, GETDATE()), -1)
Each ticket can have any number of notes attached to it. For example, if a special discount was given to a ticket holder, a note will be created about that. Similiarly, if a ticket is exchanged for another or refunded, a note will be created.
The below will return all the notes for a given Ticket based on the TicketID:
SELECT *
FROM
[Test_DB].[dbo].[Tickets]
JOIN [Test_DB].[dbo].[Notes]
ON [Test_DB].[dbo].[Tickets].[TicketID] = [Test_DB].[dbo].[Notes].[ConnectedTo]
WHERE TicketId = 64903
My question is, is there a way to combine the two? For example, the first bit of SQL could return 5 tickets, each with a different TicketID. Based on that, I want to make use of my second SQL to return all of the notes for those 5 tickets.
I was thinking of using UNION to combine the two selects... Though my brain keeps telling me that I need to JOIN the two pieces of SQL on the TicketId's, however every time I try to it comes out wrong. Any help would greatly be appreciated! Thanks.
This should work
SELECT [Test_DB].[dbo].[Tickets].*, [Test_DB].[dbo].[Notes].*
FROM [Test_DB].[dbo].[Tickets]
INNER JOIN [Test_DB].[dbo].[Movies]
ON
[Test_DB].[dbo].[Tickets].[ConnectedTo] = [Test_DB].[dbo].[Movies].[MovieID]
INNER JOIN [Test_DB].[dbo].[Notes]
ON [Test_DB].[dbo].[Tickets].[TicketID] = [Test_DB].[dbo].[Notes].[ConnectedTo]
WHERE [Test_DB].[dbo].[Tickets].[DateEntered] >= DATEADD(month, DATEDIFF(month, 0, GETDATE())-1, 0)
AND [Test_DB].[dbo].[Tickets].[DateEntered] <= DATEADD(month, DATEDIFF(month, 0, GETDATE()), -1)
I imagine that "notes" could be optional. If so, then you will want a left join rather than an inner join. Also, the use of aliases and eliminating the unnecessary square brackets would make your query easier to read:
SELECT *
FROM Test_DB.dbo.Tickets t INNER JOIN
Test_DB.dbo.Movies m
ON t.ConnectedTo = m.MovieID LEFT JOIN
Test_DB.dbo.Notes n
ON t.TicketID = n.ConnectedTo
WHERE t.DateEntered >= DATEADD(month, DATEDIFF(month, 0, GETDATE()) -1, 0) AND
t.DateEntered <= DATEADD(month, DATEDIFF(month, 0, GETDATE()), -1);
Note (no pun intended): if a ticket has multiple notes, then you will get multiple rows in the output.

I have two tables with common Quote_No and I need to sum Qty in Quote_Items with Required by Date in Table Quotes

I am trying to get the sum of "Qty" in a Table A called "Quote_Items" based on a "Required_by_Date" from Table B called Quotes. Both tables have a common "Quote_No" The required date is one month ago.
I have used the following but it produces a NULL, but I cannot see why
select sum(Qty)
from quotes.Quote_Items_Quantities
left outer join quotes.Quotes on (Quote_Required_by_Date = Qty)
WHERE (DatePart(yy, Quote_Required_by_Date) = DatePart(yy, DateAdd(m,1,getdate()))) and
datepart(m,Quote_Required_by_Date) = datepart(m,dateadd(m,1,getdate()))
Any suggestions what I am doing wrong here.
Try this:
SELECT SUM(i.Qty)
FROM Quote_Items i
JOIN Quotes q on i.Quote_No = q.Quote_No
AND CONVERT(varchar, q.Required_by_Date, 112) = CONVERT(varchar, DATEADD(month, -1, getdate()), 112)
or this (equivalent without using JOIN)
SELECT SUM(i.Qty)
FROM Quote_Items i
WHERE EXISTS(SELECT 1 FROM Quotes WHERE Quote_No = i.Quote_No AND CONVERT(varchar, Required_by_Date, 112) = CONVERT(varchar, DATEADD(month, -1, getdate()), 112))
Your query is producing NULL because of the join condition. You have
on Quote_Required_by_Date = Qty
However, the date is not going to match the quantity. Instead, you need to match on the Quote_No, according to your question:
select sum(Qty)
from quotes.Quote_Items_Quantities qiq left outer join
quotes.Quotes q
on q.Quote_Required_by_Date = qiq.Qty
WHERE (DatePart(yy, Quote_Required_by_Date) = DatePart(yy, DateAdd(m,1,getdate()))) and
datepart(m,Quote_Required_by_Date) = datepart(m,dateadd(m,1,getdate()));
You can also simplify your query by using the month() and year() functions:
select sum(Qty)
from quotes.Quote_Items_Quantities qiq left outer join
quotes.Quotes q
on q.Quote_Required_by_Date = qiq.Qty
WHERE year(Quote_Required_by_Date) = year(DateAdd(m, 1, getdate()) and
month(Quote_Required_by_Date) = month(dateadd(m,1,getdate());
Finally, you mind find it useful to use group by and get the results for many months:
select year(Quote_Required_by_Date), month(Quote_Required_by_Date), sum(Qty)
from quotes.Quote_Items_Quantities qiq left outer join
quotes.Quotes q
on q.Quote_Required_by_Date = qiq.Qty
group by year(Quote_Required_by_Date), month(Quote_Required_by_Date)
order by 1 desc, 2 desc;

Using sub-query to count specific rows

I have a query that I am using for a report. Each line is a row of data containing a medical history, the client_id is repeated for each medical history.
I'm grouping by client_id and summing their conditions but I want to use a sub-query to find any conditions that are above a preset score. My current query is giving me the total for the whole table, not just the specific client_id.
Can someone help me out? Thanks!
Here my query:
select
DATEADD(month, DATEDIFF(month, 0, taken_on), 0),
client_id,
count(hscore),
sum(hscore),
(select count(hscore)
from amexmedscreen
where hscore >= '3.5')
from amexmedscreen
group by taken_on, client_id`
It should be sufficient to use CASE to get 1 for relevant rows, and sum those:
select
...
sum(hscore),
sum(CASE WHEN hscore >= 3.5 THEN 1 ELSE 0 END)
group by taken_on, client_id`
Your subquery is a separate query. It's not constrained by what's going on in the main query. You need to tell it to do the count only for the client_id of the current record in the outer query. You'll be referring to the same table twice in two different queries, so you'll have to use a different alias for each one.
Something like this should work:
select DATEADD(month, DATEDIFF(month, 0, taken_on), 0),
client_id,
count(hscore),
sum(hscore),
(select count(hscore)
from amexmedscreen subq
where
hscore >= '3.5'
and subq.client_id = outerq.client_id )
from amexmedscreen outerq
group by taken_on, client_id
select DATEADD(month, DATEDIFF(month, 0, taken_on), 0),
client_id,
count(hscore),
sum(hscore),
tb1.COUNT_HSCORE
from amexmedscreen
INNER JOIN
(select client_id, count(hscore) as COUNT_HSCORE
from amexmedscreen
where hscore >= '3.5'
group by client_ID) as tb1
ON tb1.client_id = client id
group by taken_on, client_id,tb1.COUNT_HSCORE