I have tbl_emp like that:
empid
1
2
3
4
And tbl_att like that:
empid workingdate
1 2017-05-11
2 2017-05-13
3 2017-05-14
...........
...........
I have a job in SQL Server agent to execute step every Sunday and I want that job to insert a row for each empid with that day into tbl_att. Let's say Sunday is 2017-05-22 so I want it like that:
empid workingdate
1 2017-05-22
2 2017-05-22
3 2017-05-22
It means that I want it to insert into tbl_att for all empid with the same day (task execution day), so can anyone guide me a query that I need to put into my step command?
Try this,
INSERT INTO tbl_att SELECT empid,CAST(GETDATE() AS DATE) FROM tbl_emp;
insert into tbl_att (empid, workingdate)
Select empid,cast(getdate() as date) from tbl_emp
As you run the job on every Sunday, above query will insert the data as per your expectation I believe. FYI, But it depends on the system date
Hope it helps you
CREATE TABLE #tbl_att (empid INT,workingdate DATE)
CREATE TABLE #EmpidTab (empid INT)
INSERT INTO #EmpidTab
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4
SELECT * FROM #EmpidTab
INSERT INTO #EmpidTab
SELECT 5
INSERT INTO #tbl_att
SELECT Empid
,Getdate() AS workingdate
FROM #EmpidTab i
WHERE NOT EXISTS (
SELECT 1
FROM #tbl_att t
WHERE t.empid = i.Empid
) --Eliminate duplicte insertion of empid's
SELECT ##ROWCOUNT AS NoRowsInserted
SELECT *
FROM #tbl_att
Related
I've been creating this table manually and hoping I can automate it.
What i have in excel is a table with with days of the Month example June 1-30 what I need to do is populate the data based on sales and a separate based on accumulative ... example
Data
1 - $100
2 - $300
5 - $300
What i need to see is :
1 - $100
2 - $400
3 - $400
4 - $400
5 - $700
What my issue is the days that have 0 / no sales does not populate into the database
here is the code I have to get the data :
IF DAY (GETDATE()) = 1
SELECT Office,NetNet_Revenue_USD,NetNet_GM_USD,[DayOfMonth],[Month],[Year]
FROM Datawarehouse.dbo.Sales_History Sales_History
WHERE (Sales_History.Cust_Intercompany <> 'Yes - VAP') AND Year = (YEAR(GETDATE())) and [Period] = MONTH(GETDATE()-1)
else IF DAY (GETDATE()) <> 1
SELECT Office,NetNet_Revenue_USD,NetNet_GM_USD,[DayOfMonth],[Month],[Year]
FROM Datawarehouse.dbo.Sales_History Sales_History
WHERE (Sales_History.Cust_Intercompany <> 'Yes - VAP') AND Year = (YEAR(GETDATE())) and [Period] = MONTH(GETDATE())
Any help would be apricated as I'm over doing it manually :(
New code using the idea of joining my data to a table that has every day of the month
SELECT distinct CONVERT(DATETIME, CAST(AUDTDATE AS VARCHAR(8)), 112) as StringToDate
,Office,(NetNet_Revenue_USD),[DayOfMonth],[Month],[Year],InvoiceNumber,Revenue_Func
FROM [ACCPACAU].[dbo].[CSCRD]
left join Datawarehouse.dbo.Sales_History on Sales_History.TranDate = CONVERT(DATETIME, CAST(AUDTDATE AS VARCHAR(8)), 112)
where year(CONVERT(DATETIME, CAST(AUDTDATE AS VARCHAR(8)), 112)) = (YEAR(GETDATE()))
and
Month(CONVERT(DATETIME, CAST(AUDTDATE AS VARCHAR(8)), 112)) = MONTH(GETDATE())
One way to do this is to run a union statement to get all the office location you want, aggregate the data and then do a sum over to get a running total. I have come up with a simplified version of the same.. hope this helps you achieve what you want.
I've kept it pretty simple to show what you could do
if object_id('tempdb..#office') is not null
drop table #office
if object_id('tempdb..#data') is not null
drop table #data
;with offices as (
select 1 as office
union all
select 2 as office
union all
select 3 as office
union all
select 4 as office
union all
select 5 as office
)
Select * into #office
from offices
;with sales as (
select 1 as office , 100 as sales
union all
select 2 as office , 300 as sales
union all
select 5 as office , 300 as sales
)
Select * into #data
from sales
; with all_data as (
select #data.*
from #data
union
select office,0 as sales
from #office
where office NOT IN (select office from #data)
)
Select
office
, sales
, sum(sales) over ( order by office) as runing_total
from all_data
drop table #data
drop table #office
I have a table of data which i am using a count statement to get the amount of records for the submission date
example
AuditId Date Crew Shift Cast ObservedBy 2ndObserver AuditType Product
16 2017-06-27 3 Day B1974, B1975 Glen Mason NULL Identification Billet
20 2017-06-29 1 Day 9879 Corey Lundy NULL Identification Billet
21 2017-06-29 4 Day T9627, T9625 Joshua Dwyer NULL ShippingPad Tee
22 2017-06-29 4 Day NULL Joshua Dwyer NULL Identification Billet
23 2017-06-29 4 Day S9874 Joshua Dwyer NULL ShippingPad Slab
24 2017-06-29 4 Day Bay 40 Joshua Dwyer NULL Identification Billet
Basically I am using the following code to get my results
SELECT YEAR([Date]) as YEAR, CAST([Date] as nvarchar(25)) AS [Date], COUNT(*) as "Audit Count"
FROM AuditResults
where AuditType = 'Identification' AND Product = 'Billet'
group by Date
this returns example
YEAR Date Audit Count
2017 2017-06-27 1
2017 2017-06-29 3
Now I want to be able to retrieve all dates even if blank
so I would like the return to be
YEAR Date Audit Count
2017 2017-06-27 1
2017 2017-06-28 0
2017 2017-06-29 3
I have the following function I am trying to use:
ALTER FUNCTION [dbo].[fnGetDatesInRange]
(
#FromDate datetime,
#ToDate datetime
)
RETURNS #DateList TABLE (Dt date)
AS
BEGIN
DECLARE #TotalDays int, #DaysCount int
SET #TotalDays = DATEDIFF(dd,#FromDate,#ToDate)
SET #DaysCount = 0
WHILE #TotalDays >= #DaysCount
BEGIN
INSERT INTO #DateList
SELECT (#ToDate - #DaysCount) AS DAT
SET #DaysCount = #DaysCount + 1
END
RETURN
END
How do I use my select statement with this function? or is there a better way?
cheers
Try this;
ALTER FUNCTION [dbo].[fnGetDatesInRange]
(
#FromDate datetime,
#ToDate datetime
)
RETURNS #YourData TABLE ([Year] int, DateText nvarchar(25),[Audit Count] int)
AS
begin
insert into #YourData
SELECT
YEAR(allDates.[Date]) as YEAR,
CAST(allDates.[Date] as nvarchar(25)) AS [Date],
COUNT(r.Product) as "Audit Count"
from
(
SELECT
[date]=convert(datetime, CONVERT(float,d.Seq))
FROM
(
select top 100000 row_number() over(partition by 1 order by A.name) as Seq
from syscolumns A, syscolumns B
)d
)allDates
left join
AuditResults r on r.[Date]=allDates.[date] and r.AuditType = 'Identification' AND r.Product = 'Billet'
where
allDates.[Date]>=#FromDate and allDates.[Date]<=#ToDate
group by
allDates.[Date]
return
end
The key is the 'allDates' section ;
SELECT
[date]=convert(datetime, CONVERT(float,d.Seq))
FROM
(
select top 100000 row_number() over(partition by 1 order by A.name) as Seq
from syscolumns A, syscolumns B
)d
This will return all dates between 1900 and 2173 (in this example). Limit that as you need but a nice option. A ton of different ways to approach this clearly
you have to create another table calendar as (Mysql)- idea is the same on all RDBMS-
CREATE TABLE `calendar` (
`dt` DATE NOT NULL,
UNIQUE INDEX `calendar_dt_unique` (`dt`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;
and fill with date data.
more details
Context - I'm very new to SQL. I get the basics, and have my head around basic joins, but I'm not quite at the point of building my own querys beyond basic selects.
I have the following table layout:
Site Date Cash_1 Sales_1
4 10/04/2017 £1,500 £1,500
4 09/04/2017 NULL £1,000
4 08/04/2017 NULL £2,000
4 07/04/2017 NULL £1,000
4 06/04/2017 £5,000 £1,000
As you can see, the (example) cumulative sales between 06/04 and 09/04 for this site total the cash amount for 06/04.
This happens when site 4 fails it's overnight upload of it's cash statement - the subsequent days get rolled together in a single statement, which is dated on the first date it failed to upload.
What I'm hoping to try and get is something like the below. The idea is that the cumulative column will show the total sales since the last successful cash statement import, which will help with balance checks.
Site Date Cash_1 Sales_1 Cumulative
4 10/04/2017 £1,500 £1,500 £1,500
4 09/04/2017 NULL £1,000 £5,000
4 08/04/2017 NULL £2,000 £4,000
4 07/04/2017 NULL £1,000 £2,000
4 06/04/2017 £5,000 £1,000 £1,000
I can get my head around using "SUM(Y) as X " to create a cumulative column in the standard sense, but I can't work out how to reset the accumulation based on another columns values.
Try with ROW_NUMBER() AND Update Statement As below:
DECLARE #tblTest as Table(
SiteNo INT,
[Date] Date,
Cash INT,
Sales INT
)
INSERT INTO #tblTest VALUES(4,'10-Apr-2017',1500,1500)
INSERT INTO #tblTest VALUES(4,'09-Apr-2017',NULL,1000)
INSERT INTO #tblTest VALUES(4,'08-Apr-2017',NULL,2000)
INSERT INTO #tblTest VALUES(4,'07-Apr-2017',NULL,1000)
INSERT INTO #tblTest VALUES(4,'06-Apr-2017',5000,1000)
;With T AS
(
SELECT
*,
NULL AS Cumulative,
ROW_NUMBER() OVER(ORDER BY Date) AS RowNo
FROM #tblTest
)
SELECT
*
INTO #tblTest
FROM T
ORDER BY RowNo
DECLARE #sum INT=0
Update #tblTest
SET #sum=Cumulative=Sales+ CASE WHEN Cash IS NULL THEN #sum ELSE 0 END
SELECT * FROM #tblTest ORDER BY RowNo DESC
DROP TABLE #tblTest
I have a table of data which looks like this
ID CreatedDate
A123 2015-01-01
B124 2016-01-02
A125 2016-01-03
A126 2016-01-04
What I would like to do is group by month (as text) for this year only. I have some up with the following query but it returns data from all years not just this one:
Select Count(ID), DateName(month,createddate) from table
Where (DatePart(year,createddate)=datepart(year,getdate())
Group by DateName(month,createddate)
This returns
Count CreatedDate
4 January
Instead of
Count CreatedDate
3 January
Where have I gone wrong? I'm sure it's something to do with converting the date to month where it goes wrong
Just tested your code:
;WITH [table] AS (
SELECT *
FROM (VALUES
('A123', '2015-01-01'),
('B124', '2016-01-02'),
('A125', '2016-01-03'),
('A126', '2016-01-04')
) as t(ID, CreatedDate)
)
SELECT COUNT(ID),
DATENAME(month,CreatedDate)
FROM [table]
WHERE DATEPART(year,CreatedDate)=DATEPART(year,getdate())
GROUP BY DATENAME(month,CreatedDate)
Output was
3 January
I removed ( near WHERE
select count(id) as Count,
case when month(createddate)=1 THEN 'Januray' END as CreatedDate
from [table]
--where year(createddate)=2016 optional if you only want the 2016 count
group by month(createddate),year(createdDate)
I need to check alot of data in a Table to make sure my feed has not skipped anything.
Basically the table has the following columns
ID Datetime Price
The data in DateTime column is incremented by 1 minute in each successive row. I need to check the next row of the current one to see if is 1 minute above the one being queries in that specific context.
The query will probably need some sort of loop, then grab a copy of the next row and compare it to the datetime row of the current to make sure it is incremented by 1 minute.
I created a test-table to match your description, and inserted 100 rows with 1 minute between each row like this:
CREATE TABLE [Test] ([Id] int IDENTITY(1,1), [Date] datetime, [Price] int);
WITH [Tally] AS (
SELECT GETDATE() AS [Date]
UNION ALL
SELECT DATEADD(minute, -1, [Date]) FROM [Tally] WHERE [Date] > DATEADD(minute, -99, GETDATE())
)
INSERT INTO [Test] ([Date], [Price])
SELECT [Date], 123 AS [Price]
FROM [Tally]
Then i deleted a record in the middle to simulate a missing minute:
DELETE FROM [Test]
WHERE Id = 50
Now we can use this query to find missing records:
SELECT
a.*
,CASE WHEN b.[Id] IS NULL THEN 'Next record is Missing!' ELSE CAST(b.[Id] as varchar) END AS NextId
FROM
[Test] AS a
LEFT JOIN [Test] AS b ON a.[Date] = DATEADD(minute,1,b.[Date])
WHERE
b.[Id] IS NULL
The resullt will look like this:
Id Date Price NextId
----------- ----------------------- ----------- ------------------------------
49 2013-05-11 22:42:56.440 123 Next record is Missing!
100 2013-05-11 21:51:56.440 123 Next record is Missing!
(2 row(s) affected)
The key solution to the problem is to join the table with itself, but use datediff to find the record that is supposed to be found on the next minute. The last record of the table will of course report that the next row is missing, since it hasn't been inserted yet.
Borrowing TheQ's sample data you can use
WITH T
AS (SELECT *,
DATEDIFF(MINUTE, '20000101', [Date]) -
DENSE_RANK() OVER (ORDER BY [Date]) AS G
FROM Test)
SELECT MIN([Date]) AS StartIsland,
MAX([Date]) AS EndIsland
FROM T
GROUP BY G