Can anyone help me with this SQL Query? - sql

Update [sheet1$]
SET [Status] = 'Greater than 100M'
WHERE [Available Balance in USD] > 100000000
AND [Main Category] = 'Free Cash' AND [Sub Category] <> 'abc'
Getting an error saying
datatype mismatch error
The data type of column [Available Balance in USD] is Text. I need to convert to Int and check. Does anyone know how to do that?

In SQL Server, you would use try_convert():
WHERE TRY_CONVERT(INT, [Available Balance in USD]) > 100000000

Related

Getting 2 result columns from SQL query

I've tried to make an SQL query to get 2 result columns from 1 query. To elaborate:
This is my query:
SELECT Name, AVG(DATEDIFF(day,[Open Date],[Close Date]))
FROM Inventory Where Tested ='Yes' AND [Close Date] IS NOT NULL AND [Open Date] IS NOT NULL
GROUP BY Name
My result:
My desired result:
When also Where Tested = 'No'
How to write an SQL query with Where Tested = 'Yes' and Where Tested = 'No'? Where Tested = 'Yes' is Column 1 result and Tested = 'No' is Column 2 result.
Database:SQL server 2019
EJC answer with subqueries should already probably help with what you need, but just wanted to share some other options to achieve this:
Joining two separate queries
SELECT tested.Name, tested.TestedAVG, not_tested.NotTestedAVG FROM
(SELECT Name, AVG(DATEDIFF(day,[Open Date],[Close Date])) as "TestedAVG"
FROM Inventory
WHERE Tested ='Yes' AND [Close Date] IS NOT NULL AND [Open Date] IS NOT NULL
GROUP BY Name) tested
FULL JOIN
(SELECT Name, AVG(DATEDIFF(day,[Open Date],[Close Date])) as "NotTestedAVG"
FROM Inventory
WHERE Tested ='No' AND [Close Date] IS NOT NULL AND [Open Date] IS NOT NULL
GROUP BY Name) not_tested
ON tested.Name = not_tested.Name
Using case
SELECT Name,
AVG(CASE WHEN Tested ='Yes' THEN DATEDIFF(day,[Open Date],[Close Date]) END) as [Tested AVG],
AVG(CASE WHEN Tested ='No' THEN DATEDIFF(day,[Open Date],[Close Date]) END) as [Not Tested AVG]
FROM Inventory
WHERE [Close Date] IS NOT NULL AND [Open Date] IS NOT NULL
GROUP BY Name
Adding as group by
If you don't need to have it as a separate column, the easiest way would be to add a group by the Tested column as well.
SELECT Name, AVG(DATEDIFF(day,[Open Date],[Close Date])) as "AVG"
FROM Inventory
WHERE [Close Date] IS NOT NULL AND [Open Date] IS NOT NULL
GROUP BY Name, Tested
Then you'll get this structure:
Name
Tested
AVG
aTPO
Yes
56
aTPO
No
50
It's hard to say exactly what you want, but maybe you could use a couple of subqueries?
SELECT Name,
AVG(select DATEDIFF(i2.day,i2.[Open Date],i2.[Close Date]) from inventory i2 where i2.name = i.name and i2.Tested = 'Yes') as "Tested",
AVG(select DATEDIFF(i3.day,i3.[Open Date],i3.[Close Date]) from inventory i3 where i3.name = i.name and i3.Tested = 'No') as "Not Tested"
FROM Inventory i
Where [Close Date] IS NOT NULL AND [Open Date] IS NOT NULL
GROUP BY Name
Out of three columns if you trying to get two columns with its values, you have to specify those columns in your code.
Example:
SELECT column1, column2
FROM table_name
But if you want to find all the columns
Example:
SELECT * FROM table_name

SQL create column for every week (Loop?)

I need to make a report for weekly changes.
This is the code for todays amount
SELECT
[Entry No_],
[Customer No_],
[Posting Date],
[Description],
[Currency Code],
Trans_type = case when [Deposit]=1 then 'Deposit'
when [Imprest]=1 then 'Imprest'
else 'Other' end,
A.Amount
FROM Table1
LEFT JOIN
(
SELECT Distinct [Cust_ Ledger Entry No_],
SUM ([Amount EUR]) as 'amount'
FROM Table2
group by [Cust_ Ledger Entry No_]
having
SUM ([Amount EUR]) <> '0'
)A
on [Entry No_] = A.[Cust_ Ledger Entry No_]
Where
A.Amount is not NULL
Code to generate data for previous week is here (adding only where clause):
SELECT
[Entry No_],
[Customer No_],
[Posting Date],
[Description],
[Currency Code],
Trans_type = case when [Deposit]=1 then 'Deposit'
when [Imprest]=1 then 'Imprest'
else 'Other' end,
A.Amount
FROM Table1
LEFT JOIN
(
SELECT Distinct [Cust_ Ledger Entry No_],
SUM ([Amount EUR]) as 'amount'
FROM Table2
where [posting Date] < '2020-11-23'
group by [Cust_ Ledger Entry No_]
having
SUM ([Amount EUR]) <> '0'
)A
on [Entry No_] = A.[Cust_ Ledger Entry No_]
Where
A.Amount is not NULL
It would be enough to union both queries and then export to Excel and make pivot, but problem is that I need results of last 50 weeks. Is there any smart way to avoid union 50 tables and run one simple code to generate weekly report?
Thanks
it might be easier with sample, but I don't know how to paste table here..
Maybe it is true, i dont need union here, and group by would be enough, but it stills sounds difficult for me :)
Ok. Lets say table has such headers: Project | Country | date | amount
The code below returns amount for todays date
Select
Project,
SUM(amount)
From Table
Group by Project
I actually need todays date and also the results of previous weeks (What was the result on November 22 (week 47), November 15 (week 46) and so on.. total 50 weeks from todays date).
Code for previous week amount is here:
Select
Project,
SUM(amount)
From Table
Where Date < '2020.11.23'
Group by Project
So my idea was to create create 50 codes and join the results together, but i am sure it is a better way to do this. Besides i dont want to edit this query every week and add a new date for it.
So any ideas, to make my life easier?
if I have understood your requirement correctly, all you need to do is extract the week from the date e.g.
Select
Project,
datepart(week, date),
SUM(amount)
From Table
Where Date < '2020.11.23'
Group by Project, datepart(week, date)

How to use FORMAT ( Employee.Salary,'C',EN-US) in SUM statement ? Getting error 'Conversion Failed

I need to display 'tax wage' column in US $ format IN SQL using FORMAT function.
I am using Microsoft SQL server. Can someone please help?
Getting error:
"Conversion failed when converting the nvarchar value '$17,037.72' to data type int."
Below is the query I wrote:
SELECT EMPLOYEE.ID, EMPLOYEE.NAME, P.DEDCODE,
SUM(CASE WHEN P.DEDCODE ='SS2' THEN FORMAT(P.AMOUNT,'C','EN-US') ELSE 0 END) AS 'TAX WAGE'
FROM EMPLOYEE
JOIN P ON EMPLOYEE.ID = P.ID and EMPLOYEE.COMPANY = P.COMPANY
WHERE
P.DEDCODE ='SS2'
AND P.YEAR ='2018'
GROUP BY
EMPLOYEE.ID,
EMPLOYEE.NAME,
P.DEDCODE
I expect the tax wage column to have $70.5 as output instead of simple number 70.5
Your format function should be on SUM():
FORMAT(SUM(CASE WHEN P.DEDCODE = 'SS2' THEN P.AMOUNT ELSE 0 END),'C','EN-US') AS [TAX WAGE]
You already included WHERE clause with P.DEDCODE ='SS2' then why you need conditional aggregation, it should be only
SELECT . . . ,
FORMAT(SUM(P.DEDCODE),'C','EN-US') AS [TAX WAGE]
. . .

SUM of columns from different tables

here is my data,
Table 1:
STORAGE HANDLING TOTAL BILLING
--------------------------------------
1300 10900
0 10950
0 6000
0 5950
Table 2:
LINER REVENUE
---------------
1300
250
3000
200
I need to calculate Total Billing:
I tried with this code.
UPDATE [dbo].[FCLOverall] SET [Total Revenue] = SELECT SUM([STORAGE]), SUM([HANDLING]), SUM([LINER Revenue])
FROM (SELECT [STORAGE], [HANDLING],[Container No]
FROM [dbo].[FCLOverall]
UNION ALL
SELECT [Container No],[LINER Revenue]
FROM [dbo].[FCL_Child])
It is throwing some error missing brackets and invalid keyword select. is the query is right or wrong?
Can someone guide a query how to calculate on this?
does you find something below
UPDATE [dbo].[FCLOverall]
SET [Total Revenue] =
(SELECT SUM([STORAGE])+ SUM([HANDLING]) + SUM([LINER Revenue] ) as s
FROM (
SELECT [Container No],[STORAGE], [HANDLING],0
FROM [dbo].[FCLOverall]
UNION ALL
SELECT [Container No],0,0,[LINER Revenue]
FROM [dbo].[FCL_Child]
) t )
Give this a try based on the assumption that Container No is key field.
UPDATE U
SET U.[Total Revenue] = COALESCE(U.Storage,0) + COALESCE(U.Handling,0) + COALESCE(FCLC.[Liner Revenue],0)
FROM dbo.FCLOverall AS U
INNER JOIN dbo.FCL_Child AS FCLC
ON U.[Container No] = FCLC.[Container No]
Try this:
UPDATE FO
SET [FO.Total Revenue] = ISNULL(FO.[STORAGE], 0) + ISNULL(FO.[HANDLING], 0) + ISNULL(FC.[LINER Revenue],0)
FROM [dbo].[FCLOverall] AS FO
INNER JOIN [dbo].[FCL_Child] FC on FO.[FO.Container No] = FC.[Container No]

Adding a number to a datetime to get new date SQL Server

I am trying to get the query below to assign a number value to the column 'DESIRED TRANSIT TIME' based on the value in that column - 10 if it starts with A and 5 if it starts with C. From there I want to add that number to REVISED_EX_FACTORY to get a new ex factory. I have never attempted this and using the query below I get the result which is the date plus the text 'DESIRED TRANSIT TIME' - which kind of makes sense since it is a string. How can I get the value in the column instead of the textual name of the column in line 20? I was told converting the datetime values to get rid of the time component was a good way to go.
The ideal result would be to either add 5 or 10 days to the date depending the value in 'DESIRED TRANSIT TIME'
SQL:
USE PDX_SAP_USER
GO
SELECT E.team_member_name [EMPLOYEE],
K.business_segment_desc [BUSINESS SEGMENT],
G.order_status [GPS ORDER STATUS],
H.po_type [PO TYPE],
G.order_no [GPS ORDER NO],
I.po_number [SAP PO NUMBER],
I.shipping_instruct [SAP SHIP MODE],
G.shipping_type [GPS SHIP MODE],
CASE
WHEN I.shipping_instruct LIKE 'A%'
THEN '10'
WHEN I.shipping_instruct LIKE 'C%'
THEN '5'
END [DESIRED TRANSIT TIME],
CONVERT(VARCHAR(12),I.revised_ex_factory,101) [LAST CONFIRMED DATE ],
CONVERT(VARCHAR(12),I.revised_ex_factory,101) + 'DESIRED TRANSIT TIME' AS 'PROPOSED ETA',
CONVERT(VARCHAR(12),S.po_estimated_deliv_date,101) [CURRENT DELIV DATE],
-- 'days_diff'
I.material [MATERIAL],
M.description [DESCRIPTION],
I.stock_category [STOCK CATEGORY],
I.po_ordered_quantity [PO ORDERED QUANTITY],
I.po_recvd_quantity [PO RECVD QUANTITY],
I.po_balance_quantity [PO BALANCE QUANTITY],
I.po_intransit_quantity [PO INTRANSIT QUANTITY],
I.plant_code [PLANT],
I.direct_ship_code [DS CODE],
I.comment [COMMENT]
FROM (SELECT order_no,
order_status,
shipping_type
FROM asagdwpdx_prod.dbo.SimoxOrder1
UNION ALL
SELECT order_no,
order_status,
shipping_type
FROM asagdwpdx_prod.dbo.SimoxOrder2
UNION ALL
SELECT order_no,
order_status,
shipping_type
FROM asagdwpdx_prod.dbo.SimoxOrder3) G
JOIN pdx_sap_user..vw_po_header H ON G.order_no = H.ahag_number
JOIN pdx_sap_user..vw_po_item I ON H.po_number = I.po_number
JOIN pdx_sap_user..vw_po_size S ON I.po_number = S.po_number
AND I.po_item_number = S.po_item_number
JOIN pdx_sap_user..vw_mm_material M ON I.material = M.material
JOIN pdx_sap_user..vw_kd_business_segment K ON M.business_segment_code = K.business_segment_code
JOIN adi_user_maintained..scm_po_employee_name E ON I.po_number = E.po_number
WHERE I.po_balance_quantity > 0
AND I.del_indicator NOT IN ('L','S')
AND H.PO_TYPE NOT IN ('01','UB')
AND I.shipping_instruct IN ('A1','A2','A5','C1','C2','C3')
SAMPLE RESULT:
04/30/2016DESIRED TRANSIT TIME
So you have two options. The first is to duplicate the CASE statement you have a second time, and concatenate that with the date. That's probably the most straight forward, although you will end up duplicating that code. It's a small duplication, but one none the less. If that bothers you, or you need to use it elsewhere in your query as well, you will need to wrap the whole thing in a subquery so you can reference the case statement as though it were a distinct column. e.g.
select
...
DesiredTransitTime =
case
when I.shipping_instruct LIKE 'A%'
then '10'
when I.shipping_instruct LIKE 'C%'
then '5'
end,
ProposedETA = convert(varchar(12),I.revised_ex_factory,101) +
case
when I.shipping_instruct LIKE 'A%'
then '10'
when I.shipping_instruct LIKE 'C%'
then '5'
end
...
or
select
[DESIRED TRANSIT TIME],
[PROPOSED ETA = StringDate + [DESIRED TRANSIT TIME]
...
from
(
select
StringDate = convert(varchar(12), I.revised_ex_factory,101) ,
[DESIRED TRANSIT TIME] =
case
when I.shipping_instruct LIKE 'A%'
then '10'
when I.shipping_instruct LIKE 'C%'
then '5'
end,
...
) a