Is there a way in which I can insert data from one table into another when today is Monday?
I tried making something like the below, using CASE WHEN, however it doesn't quite work right, any help would be welcomed
INSERT INTO [dbo].[WF_All]
SELECT (CASE WHEN (DATENAME(WEEKDAY,FLOOR(convert(float,getdate()))))='MONDAY' THEN
(
SELECT [Parent Number]
,[Parent Name]
,[Customer Number]
,[Customer Name]
,[Collector]
,[Outstanding]
FROM dbo.[Invoices]
)
ELSE NULL END )
yes , like this :
INSERT INTO [dbo].[WF_All]
SELECT [Parent Number]
,[Parent Name]
,[Customer Number]
,[Customer Name]
,[Collector]
,[Outstanding]
FROM dbo.[Invoices]
WHERE DATENAME(WEEKDAY,GETDATE()) = 'Monday'
or
... WHERE DATEPART(WEEKDAY, GETDATE()) = 2 --Monday
Is this what you want.
if datename(weekday,getdate()) = 'MONDAY' then
INSERT INTO [dbo].[WF_All] (
-- column names go here
)
SELECT [Parent Number]
,[Parent Name]
,[Customer Number]
,[Customer Name]
,[Collector]
,[Outstanding]
FROM dbo.[Invoices]
Related
I have the following example Data set that was created by the following query that sets an employee as "Active' or 'Inactive" based on if they worked any hours during a month.
Select Concat([First Name],' ', [Last Name]) AS 'FullName',
CASE (SUM([Week 1] + [Week 2] + [Week 3] + [Week 4]))
When 0 Then 'Inactive'
ELSE 'Active'
END [Status]
From dbo.hours
Group by [first name], [last name]
FullName
Status
Alan Brewer
Active
Alejandro McGuel
Inactive
Alex Nayberg
Active
Im trying to get rid of all the 'Active' Status rows so that my query only displays those who are 'inactive'. I attempted to add WHERE Status = Inactive between the FROM and GROUP BY expression but it returns no results. (Does not give an error, just returns empty columns).
Anyone know what I am missing?
You can't add a WHERE condition on the Status column just like that since it's not available to WHERE clause .. you can use that query as inline view and do the condition check in outer query like
select * from (
Select Concat([First Name],' ', [Last Name]) AS 'FullName',
CASE (SUM([Week 1] + [Week 2] + [Week 3] + [Week 4]))
When 0 Then 'Inactive'
ELSE 'Active'
END [Status]
From dbo.hours
Group by [first name], [last name] ) xxx
where Status != 'Active';
You need a HAVING clause, but also for your requirement you don't need the CASE expression:
SELECT CONCAT([First Name],' ', [Last Name]) AS FullName,
'Inactive' [Status]
FROM dbo.hours
GROUP BY [first name], [last name]
HAVING SUM([Week 1] + [Week 2] + [Week 3] + [Week 4]) = 0
CTE will work as well:
with cte as(
Select Concat([First Name],' ', [Last Name]) AS 'FullName',
CASE (SUM([Week 1] + [Week 2] + [Week 3] + [Week 4]))
When 0 Then 'Inactive'
ELSE 'Active'
END [Status]
From dbo.hours
Group by [first name], [last name])
select FullName from cte where Status <> 'Active'
How can I use Sum, Cast and Partition by functions together?
I get error.
Conversion failed when converting the nvarchar value '693.41' to data
type int."
I tried this
SUM(CAST([total price] AS INT)) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
Full query is at the below.
SELECT
ID,
[Project Manager],
Job#,
[Date],
[Job Type],
first_value([Job Name]) OVER (PARTITION BY value_partition ORDER BY ID) CustomerGroup, Value_Partition
Customer,
[Sales Rep1],
DeliveryType,
ProjectType,
[Item Price],
[Service Price],
[Total Price],
SUM(CAST([total price] AS INT)) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
FROM (
SELECT
ID,
[Project Manager], Job#, [Date], [Job Type], [Job Name],Customer,[Sales Rep1],DeliveryType,ProjectType,[Item Price],[Service Price],[Total Price],
SUM(CASE WHEN [JOB NAME] IS NULL THEN 0 ELSE 1 END) OVER (ORDER BY ID) AS Value_Partition
FROM Testing2
WHERE
[Date] IS NOT NULL AND
([Date] NOT LIKE '0' OR JOB# NOT LIKE '0' OR [JOB TYPE] NOT LIKE '0')
AND [Project Manager] NOT LIKE 'ITEM / SERVICE'
) AS X
First, identify the rows that have problems. You are converting to an int, so:
select price
from Testing2
where try_convert(int, price) is null and price is not null;
At least some of the values will have decimal points (as in your example). To see if this is the only problem, I would suggest converting to a decimal next:
select price
from Testing2
where try_convert(decimal(20, 4), price) is null and price is not null;
If this returns nothing, you are set. If not, you will need to figure out how to address these exceptions.
Then, I would phrase the calculation using decimals and not floats:
SUM(TRY_CAST([total price] AS DECIMAL(20, 4))) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
Monetary amounts should generally be represented using fixed-point values rather than approximate floating point values. The issue with floating point values is that information may be lost. Consider this example with reals:
select cast(1000000 as real) + cast(0.01 as real),
cast(1000000 as decimal(20, 4)) + cast(0.01 as decimal(20, 4))
Integer will not have decimal values, and it will throw an error.
If I use this, similar to the example you have.
Declare #val nvarchar(10) = '10.24'
select cast (#val as int)
I get this following error.
Msg 245, Level 16, State 1, Line 3
Conversion failed when converting the nvarchar value '10.24' to data type int.
Now to avoid this error, I can round the digit to 0 decimal places and convert as Int. Also, I would recommend to use Try_Cast to avoid any cases of actual nvarchar values(it would convert it to null) if you are using sql server 2012 or more.
Declare #val nvarchar(10) = '10.24'
select Try_cast (round(#val,0) as int) as valuen
Output, I think this will work in your sum function.
valuen
10
Why don't you cast it in inner query with decimal(16,9) instead of int
SELECT
ID,
[Project Manager],
Job#,
[Date],
[Job Type],
first_value([Job Name]) OVER (PARTITION BY value_partition ORDER BY ID) CustomerGroup, Value_Partition
Customer,
[Sales Rep1],
DeliveryType,
ProjectType,
[Item Price],
[Service Price],
[Total Price],
SUM([total price]) OVER (PARTITION BY (ProjectType)) as TotalPriceV2
FROM (
SELECT
ID,
[Project Manager], Job#, [Date], [Job Type], [Job Name],Customer,[Sales Rep1],DeliveryType,ProjectType,[Item Price],[Service Price],cast([Total Price] as decimal(16,9)) as [Total Price],
SUM(CASE WHEN [JOB NAME] IS NULL THEN 0 ELSE 1 END) OVER (ORDER BY ID) AS Value_Partition
FROM Testing2
WHERE
[Date] IS NOT NULL AND
([Date] NOT LIKE '0' OR JOB# NOT LIKE '0' OR [JOB TYPE] NOT LIKE '0')
AND [Project Manager] NOT LIKE 'ITEM / SERVICE'
) AS X
If you have a combination of string and number as your column value and you want to sum up the number. For SQL Server 2012+ you can use TRY_CAST or TRY_CONVERT to avoid any casting errors.
TRY_CAST (Transact-SQL)
In your scenario, you are not using proper data type for casting, you have values like 693.41 which can't be casted to INT, instead you should use DECIMAL datatype.
One more suggestion, instead of using NOT LIKE, better use <> in SQL Server like following.
Change
([Date] NOT LIKE '0' OR JOB# NOT LIKE '0' OR [JOB TYPE] NOT LIKE '0')
to
([Date] <> '0' OR JOB# <> '0' OR [JOB TYPE] <> '0')
One possible solution is to firstly convert the nvarchar value to decimal and then to integer:
CAST(CAST([total price] AS FLOAT) AS INT)
However, in this way the decimal part is lost if it matters to you.
Could you take a look at the query below please? I tried to convert my access table into a SQL query with very little knowledge (for now).
The last line seems to be wrong when I execute it.
USE [idb_datastore]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[idb_dataSTORESQLTesting]
AS
IF OBJECT_ID( 'idb_datastore.dbo.[Testing]','U' ) IS NOT NULL
DROP TABLE idb_datastore.dbo.[Testing];
SELECT dbo.REC_HDR.F91 AS [PO Number],
hd.F1032 AS [Trs Number],
hd.F76 AS [Order Date],
hd.F27 AS [Vendor ID],
hd.F334 AS [Vendor Name],
hd.F1246 AS [Delivery Date],
hd.F1127 AS [Operator Short Name],
hd.F1068 AS State,
hd.F1067 AS Status
FROM SMSSERVER01.STORESQL.dbo.REC_HDR hd
WHERE hd.F91 Is Not Null AND hd.F76 >= Convert(datetime, ’2017/01/01’ ) AND
hd.F1068 NOT like ’Voided’
Here
SQL datetime format is yyyy-mm-dd hh:mm:ss
change the final line to this
Convert(datetime, '2017-01-01' )
Change the where sentence to this
WHERE hd.F91 Is Not Null
AND hd.F76 >= CONVERT(DATETIME, '03/13/2013', 101)
AND hd.F1068 NOT like '%Voided%'
I am attempting to define and new column called End Year that is the calculation of another column plus a number representing number of years. For some reason my script does not recognize the new column called Allocation Year using the excerpt below SQL statement in SQL Server 2008. Note that Contract Year is an existing column that is identified in the non-redacted full script:
,[Allocation Type] =
CASE
WHEN left([contract type] ,1)'1' = THEN 'O&M'
ELSE 'N/A'
END
,[Allocation Year] =
CASE
WHEN [Contract Year]='XXXX' THEN '0'
ELSE CAST ([Contract Year] AS INT)
END
,[End Year] =
CASE
WHEN [Allocation Type]='O&M' THEN [Allocation Year] + 6
END
Columns are named with the AS keyword (which can also be elided in many cases), not with the = operator.
SQL Server does not let you reference other columns or aliases in a SELECT clause - you have to use a subquery:
Like so:
SELECT
*,
CASE WHEN [Allocation Type] = 'O&M'
THEN [Allocation Year Temp] + 6
ELSE NULL
END AS [Allocation Year]
FROM
(
SELECT
CASE WHEN LEFT( [Contract type], 1 ) = '1'
THEN 'O&M'
ELSE 'N/A'
END AS [Allocation Type],
CASE WHEN [Contract Year] = 'XXXX'
THEN '0'
ELSE CAST( [Contract Year] AS int )
END AS [Allocation Year Temp],
*
FROM
....
)
If you want to put everything in one select query, then try this one. Hope this helps. Thanks.
,[End Year] =
CASE
WHEN left([contract type] ,1)='1' THEN
(CASE
WHEN [Contract Year]='XXXX' THEN 6
ELSE (CAST ([Contract Year] AS INT) + 6 )
END)
END
You cannot reference computed columns in the SELECT statement. You'll have to repeat the calculation (or use subqueries like Dai suggested):
,[Allocation Type] =
CASE
WHEN left([contract type] ,1)='1' THEN 'O&M'
ELSE 'N/A'
END
,[Allocation Year] =
CASE
WHEN [Contract Year]='XXXX' THEN 0
ELSE CAST ([Contract Year] AS INT)
END
,[End Year] =
CASE
WHEN left([contract type] ,1)='1' THEN (CASE
WHEN [Contract Year]='XXXX' THEN 0
ELSE CAST ([Contract Year] AS INT)
END) + 6
END
Hoping someone can help me. I was able to put together this SQL script but it coming back with minor errors here and there. I'be been trying to debug for over a week now. Please help. the first error message is "Incorrect syntax near ')'." If you fixe that it keeps on throwing more out so I'm thinking I'm not coding this correctly. I am unable to save changes that do work. it tell me the save request was aborted. Working with SQL Server 2008 r2
SELECT
PublicationID AS PubID, (PubNum + '- ' + PubTitle) AS [Pub Descr],
CONVERT(Varchar(10), [Datestamp], 101) AS [Date Printed],
QtyPrinted AS [Qty Printed],
[2] AS [Tyler Inventory],
[1] AS [Central Inventory],
[3] AS [Mailing House Inventory],
(
SELECT SUM(S)
FROM
(
SELECT [1] UNION ALL
SELECT [2] UNION ALL
SELECT [3]
) AS T (S)) AS [Current Inventory],
RecycledQty AS [Recycled],
MailingVendorName AS [Mailing Vendor],
PrintVendorName AS [Print Vendor]
FROM
(
SELECT
PublicationID, LocationID, Balance, PubNum,
PubTitle, ItemPerCase, Datestamp, Deleted,
RecycledQty, MailingVendorName, PrintVendorName,
QtyPrinted
FROM
(
dbo.view_PubInventory_Main_Summary_RAW) x PIVOT (sum(balance) FOR
LocationID IN ([1], [2], [3])) p)
SELECT *
FROM
(SELECT PUBID, [Pub Descr], [Date Printed], [Qty Printed],
[Tyler Inventory], [Central Inventory],
[Mailing House Inventory], [Current Inventory], [Recycled],
[Mailing Vendor]
FROM GG
) AS T
Hard to follow exactly what you're after, but I think you want Current Inventory to just be [1]+[2]+[3], and you didn't alias your subquery. The query at the bottom looks fine.
SELECT PublicationID AS PubID
, PubNum + '- ' + PubTitle AS [Pub Descr]
, CONVERT(VARCHAR(10), [Datestamp], 101) AS [Date Printed]
, QtyPrinted AS [Qty Printed]
, [2] AS [Tyler Inventory]
, [1] AS [Central Inventory]
, [3] AS [Mailing House Inventory]
, [1]+[2]+[3] AS [Current Inventory]
, RecycledQty AS [Recycled]
, MailingVendorName AS [Mailing Vendor]
, PrintVendorName AS [Print Vendor]
FROM ( SELECT PublicationID
, LocationID
, Balance
, PubNum
, PubTitle
, ItemPerCase
, Datestamp
, Deleted
, RecycledQty
, MailingVendorName
, PrintVendorName
, QtyPrinted
FROM dbo.view_PubInventory_Main_Summary_RAW
PIVOT ( SUM(balance) FOR LocationID IN ( [1], [2], [3] ) ) p
)AS Sub