I need help in an sql query - sql

I have a table where the attendance of the employees is recorded. We only insert the present days. I want to show all dates of the month along with recorded attendance days. where not recorded days will show absent. Need Help.
Here is the Table Employee Attendance. Please Note that We only insert Present days into this table. Absent and Holidays are not inserted into this table.
`CREATE TABLE [dbo].[EmployeeAttendance](
[CompanyCode] [int] NOT NULL,
[BranchCode] [int] NOT NULL,
[TransactionDate] [datetime] NOT NULL,
[EmployeeCode] [int] NOT NULL,
[AttendanceCount] [int] NOT NULL,
[ShiftCode] [int] NOT NULL,
[ScheduledTimeIn] [datetime] NULL,
[ScheduledTimeOut] [datetime] NULL,
[BreakStartTime] [datetime] NULL,
[BreakEndTime] [datetime] NULL,
[FlexiLateTime] [int] NULL,
[FlexiEarlyTime] [int] NULL,
[RecordedTimeIn] [datetime] NULL,
[RecordedTimeOut] [datetime] NULL,
[RemarksIn] [varchar](500) NULL,
[RemarksOut] [varchar](500) NULL,
[AddByUserId] [int] NULL,
[AddDateTimeIn] [datetime] NULL,
[AddDateTimeOut] [datetime] NULL,
CONSTRAINT [PK_EmployeeAttendance_1] PRIMARY KEY CLUSTERED
(
[CompanyCode] ASC,
[BranchCode] ASC,
[TransactionDate] ASC,
[EmployeeCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]`

First: You need to create a "table" that has all the days of the month in it. Then you left join your recorded attendance data to that range of dates.
SELECT d.date, a.*
FROM [dates] AS d -- this is a set of rows, one per needed date
LEFT JOIN EmployeeAttendance AS a ON d.[date] = a.[RecordedTimeIn]
Now, depending on the database being used, you can generate the needed date rows in a variety of ways (eg a recursive common table expression).
Regardless of method you need one row per date is your first step and this will be the "from" table.

Related

Sql server database store procedure query

I have two tables as below:
1) UserFavouriteCurrencies
CREATE TABLE [dbo].[UserFavouriteCurrencies](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[UserId] [int] NULL,
[CurrencyId] [int] NULL,
[EntryDate] [datetime] NULL,
CONSTRAINT [PK_UserFavouriteCurrencies] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Above table is holding data of user favorite companies
2) CurrencyRates
CREATE TABLE [dbo].[CurrencyRates](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[CurrencyId] [int] NULL,
[Price] [float] NULL,
[Open_24h] [float] NULL,
[Volume_24h] [float] NULL,
[Low_24h] [float] NULL,
[High_24h] [float] NULL,
[Volume_30d] [float] NULL,
[BestBid] [float] NULL,
[BestAsk] [float] NULL,
[TradeId] [bigint] NULL,
[PriceDate] [datetime] NULL,
[PriceDateTimestamp] [bigint] NULL,
[OpenInterest] [float] NULL,
CONSTRAINT [PK_CoinbaseTickerRatesMaster] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Above table holds rates details of currencies.
Call : EXEC sp_Getdata 1(Here 1 in UserId of UserFavouriteCurrencies table)
I need all records for particular currencies last latest records in one query as below
DECLARE #Today DATETIME = GETDATE(), #PrevDate DATETIME = GETDATE()<br>
SELECT TOP 1 Price, PriceDate, Volume_24h, PriceDateTimestamp
FROM CurrencyRates
WHERE CurrencyId = #CurrencyId AND PriceDate <= #Today
ORDER BY PriceDateTimestamp DESC
Above query is only select data for one particular currency but I need the data related to user which added on UserFavouriteCurrencies table.
Please help me to write store procedure for this query
Thanks in advance.
For each currency in UserFavouriteCurrencies Table, consider the query below
SELECT
uc.Id -- This is the userId
,cr.Price
,cr.PriceDate,
,cr.Volume_24h
,cr.PriceDateTimestamp
FROM
UserFavouriteCurrencies AS uc
INNER JOIN CurrencyRates AS cr -- See Hints : 1
ON cr.CurrencyId = uc.CurrencyId
WHERE
PriceDate <= GETDATE()
AND
uc.Id = #Id
-- You can add other Predicates Here...
Hints:
Consider using LEFT OUTER JOIN if user's currency may not exist in CurrencyRates
!This will however introduce NULLs which you must handle

SQL get duplicates created within n seconds, update f key row in other table, delete dups

I have a table InspectionNotes - I am able to get duplicate notes that are created within n seconds - this works well.
Problem is when I try to delete where rn > 1 I hit a foreign key constraint - in
InspectionHoldDurations column PutOnHoldNoteID.
table Inspection Notes:
CREATE TABLE [dbo].[InspectionNotes](
[InspectionNoteID] [uniqueidentifier] NOT NULL,
[InspectionID] [uniqueidentifier] NOT NULL,
[UserRoleID] [uniqueidentifier] NOT NULL,
[Notes] [nvarchar](max) NOT NULL,
[CurrentInspectionStatusID] [int] NOT NULL,
[CreatedOn] [datetime] NOT NULL,
[InspectionNoteTypeID] [int] NOT NULL,
[QuickAnswerID] [uniqueidentifier] NULL,
[Reviewed] [bit] NOT NULL CONSTRAINT [DF_InspectionNotes_Reviewed] DEFAULT ((0)),
[DateReviewed] [datetime] NULL,
[ReviewedByUserRoleID] [uniqueidentifier] NULL,
CONSTRAINT [PK_InspectionNotes] PRIMARY KEY CLUSTERED
Table InspectionHoldDurations
CREATE TABLE [dbo].[InspectionHoldDurations](
[InspectionHoldDurationID] [uniqueidentifier] NOT NULL,
[InspectionID] [uniqueidentifier] NOT NULL,
[PutOnHoldByRoleID] [uniqueidentifier] NOT NULL,
[TookOffHoldByRoleID] [uniqueidentifier] NULL,
[StartDate] [datetime] NOT NULL,
[EndDate] [datetime] NULL,
[TotalHoldDurationMinutes] [int] NULL,
[ExpirationDate] [datetime] NULL,
[PutOnHoldNoteID] [uniqueidentifier] NULL,
[TakeOffHoldNoteID] [uniqueidentifier] NULL,
PRIMARY KEY CLUSTERED
(
[InspectionHoldDurationID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
My current query to delete duplicates:
;WITH CTE1
AS (
SELECT
[InspectionNoteID],
ROW_NUMBER() OVER (partition by InspectionID, Notes,UserRoleID,CurrentInspectionStatusId,InspectionNoteTypeID,QuickAnswerID,Reviewed,DateReviewed,ReviewedByUserRoleID,DATEDIFF(ss,'1/1/1970',CreatedOn) / 10000 ORDER BY createdon ASC) AS rn
FROM [DBO].[InspectionNotes]
)
DELETE inote
FROM
[DBO].[InspectionNotes] inote
INNER JOIN
CTE1
ON inote.InspectionNoteID = CTE1.[InspectionNoteID]
where CTE1.rn > 1
AND NOT EXISTS (SELECT * FROM [DBO].[InspectionHoldDurations] WHERE PutOnHoldNoteID = CTE1.InspectionNoteID or TakeOffHoldNoteID = CTE1.InspectionNoteID)
I want to get rid of the AND NOT EXISTS (SELECT * FROM [DBO].[InspectionHoldDurations] and instead update this table with corresponding row from CTE1 where rn = 1 - then delete from InspectionNotes where rn > 1. I have tried this and keep getting fkey error.

Conversion failed when converting date and/or time from character string. What could be wrong?

INSERT INTO dbo.SaleNew(ENQ_AID,DOCKET_NO,SALE_TYPE,VEHICLE_MODEL,SALE_DATE,BOOKING_DATE,DELIVERY_DATE,
DEALER_NAME,ENQ_GEN_BY,EXEC_NAME,USER_CR,DATE_CR) SELECT '6','2','0','TEST','2016-05-01','2016-05-10','2016-05-15',
'ABC','S I','V B','1',SWITCHOFFSET(SYSDATETIMEOFFSET(), '+05:30')
What could be wrong with this query?
Also tried:
INSERT INTO dbo.SaleNew(ENQ_AID,DOCKET_NO,SALE_TYPE,VEHICLE_MODEL,SALE_DATE,BOOKING_DATE,DELIVERY_DATE,
DEALER_NAME,ENQ_GEN_BY,EXEC_NAME,USER_CR,DATE_CR) SELECT '6','2','0','TEST',CONVERT(DATE,'01/05/2016',103),CONVERT(DATE,'10/05/2016',103),
CONVERT(DATE,'15/05/2016',103),'ABC','S I','V B','1',SWITCHOFFSET(SYSDATETIMEOFFSET(), '+05:30')
This is the create table query:
CREATE TABLE [dbo].[SaleNew](
[SALE_ID] [int] IDENTITY(1,1) NOT NULL,
[ENQ_AID] [bigint] NOT NULL,
[DOCKET_NO] [varchar](50) NOT NULL,
[VEHICLE_MODEL] [varchar](100) NOT NULL,
[SALE_DATE] [date] NULL,
[BOOKING_DATE] [date] NULL,
[DELIVERY_DATE] [date] NULL,
[DEALER_NAME] [date] NULL,
[ENQ_GEN_BY] [varchar](100) NULL,
[EXEC_NAME] [varchar](100) NULL,
[USER_CR] [int] NULL,
[DATE_CR] [date] NULL,
[USER_UP] [int] NULL,
[DATE_UP] [date] NULL,
[SALE_TYPE] [int] NOT NULL,CONSTRAINT [PK_SaleNew] PRIMARY KEY CLUSTERED (
[SALE_ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON ) ON [PRIMARY]
What could be the reason?
DEALER_NAME type is defined as DATE but you want to INSERT a VARCHAR type value ABC in it.
Execute following query in order to edit the mentioned column type, then Execute your INSERT query.
ALTER TABLE [dbo].[SaleNew]
ALTER COLUMN [DEALER_NAME] VARCHAR(50) NULL

Date time index sql server 2005

I know this is a common topic but i stil feel my scenario requires some custom advice. I was selecting from a table the other day and it took me an AGE to select on a datetime column that has not been indexed. I want to index this, only problem ebing is that the "production" 2005 box i am unfamiliar with and how it will handle the index creation. With that in mind i am wondering what the safest way for me to create an index on the table is. All the details i think people will need are below (i hope) :
Index to be created on field 5 (possibly field4 also)
Table 1 definition:
CREATE TABLE [dbo].[TABLE 1](
[ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_BLA] DEFAULT (newid()),
[field1] [nvarchar](7) NULL,
[field2] [nvarchar](10) NULL,
[field3] [nvarchar](2) NULL,
[field4] [datetime] NULL,
[field5] [datetime] NULL,
[field6] [smallint] NULL,
[field7] [nvarchar](1) NULL,
[field8] [nvarchar](7) NULL,
[field9] [nvarchar](60) NULL,
[field10] [smallint] NULL,
[field11] [nvarchar](15) NULL,
[field12] [datetime] NULL,
CONSTRAINT [PK_ID] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Total count of rows in Table 1 : 2926836

Select all rows from table having two given values anywhere in rows

I have a table of bus route. this table has fields like bus no. , route code , starting point , end point, and upto 10 halts from halt1 , halt2...halt10 . i have filled data in this table. now i want to select all rows having two values,for example jaipur and vasai. in my table, there are two rows that have jaipur and vasai. In one row, jaipur is in column halt2 and vasai in halt9. Similarly another row has jaipur in halt4 column and vasai in halt10 column.
please help me to find out sql query. I am using MS SQL server.
scrip
USE [JaipuBus]
GO
/****** Object: Table [dbo].[MyRoutes] Script Date: 02/24/2014 13:28:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[MyRoutes](
[id] [int] IDENTITY(1,1) NOT NULL,
[Route_No] [nvarchar](50) NULL,
[Route_Code] [nvarchar](50) NULL,
[Color] [nvarchar](50) NULL,
[Start_Point] [nvarchar](200) NULL,
[End_Point] [nvarchar](200) NULL,
[halt1] [nvarchar](50) NULL,
[halt2] [nvarchar](50) NULL,
[halt3] [nvarchar](50) NULL,
[halt4] [nvarchar](50) NULL,
[halt5] [nvarchar](50) NULL,
[halt6] [nvarchar](50) NULL,
[halt7] [nvarchar](50) NULL,
[halt8] [nvarchar](50) NULL,
[halt9] [nvarchar](50) NULL,
[halt10] [nvarchar](50) NULL,
CONSTRAINT [PK_MyRoutes] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
use CONTAINS
SELECT *
WHERE CONTAINS((startingpoint,endpoint,halt1,halt2,halt3,halt4,halt5,halt6,halt7,halt8,halt9,halt10), 'jaipur')
AND CONTAINS((startingpoint,endpoint,halt1,halt2,halt3,halt4,halt5,halt6,halt7,halt8,halt9,halt10), 'vasai');
SELECT * FROM bus_rout WHERE (halt1='aaa' OR halt2='aaa' OR .... halt10='aaa') AND (halt1='bbb' OR halt2='bbb' OR ....... halt10='bbb')
The where clause could be generated by code.
Based on your input, it seems to be a necessity for you to have Normalized table structure.
CREATE TABLE [dbo].[MyRoutes](
[id] [int] IDENTITY(1,1) NOT NULL,
[Route_No] [nvarchar](50) NULL,
[Route_Code] [nvarchar](50) NULL,
[Color] [nvarchar](50) NULL,
[Start_Point] [nvarchar](200) NULL,
[End_Point] [nvarchar](200) NULL,
[HaltNum] INT,
[Halt] [nvarchar](50) NULL
)
Then a query to solve the routes problem can be written as below:
SELECT a.Route_No, a.Route_Code, a.Color, a.Start_Point, a.End_Point,
a.HaltNum StartNum, b.HaltNum StopNum
FROM MyRoutes a
INNER JOIN MyRoutes b
ON a.id = b.id
WHERE a.Halt = 'jaipur' AND b.Halt = 'vasai'
AND a.HaltNum < b.HaltNum
Even better design of the table structure would be to have a separate master table for all Stops where you can maintain only StopId and StopName. In the MyRoutes table then you can have HaltId as foreign key referencing StopId column of the all stops master table. The above query would then need to inner join with this table twice to have conditions on StopName