Recently I've faced weird issue. I have two simple queries where one of them uses TOP X and other one does the same by using ROW_NUMBER and then selects items with rowNumber between 1 and X, and both of them ordered by same column, but the result is completely different.
For example, let's say we have a simple DB as below with some dummy data:
CREATE TABLE [dbo].[Test](
[Id] [int] IDENTITY(1,1) NOT NULL,
[NDate] [datetime] NOT NULL,
CONSTRAINT [PK_Test] 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]
SET IDENTITY_INSERT [dbo].[Test] ON
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (1, '2011-08-24 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (2, '2011-08-24 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (3, '2011-08-24 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (4, '2011-08-24 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (5, '2011-08-21 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (6, '2011-08-21 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (7, '2011-08-21 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (8, '2011-08-21 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (9, '2011-08-21 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (10, '2011-08-21 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (11, '2011-08-21 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (12, '2011-08-21 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (13, '2011-08-21 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (14, '2011-08-21 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (15, '2011-08-21 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (16, '2011-08-21 00:00:00.000')
SET IDENTITY_INSERT [dbo].[Test] OFF
Now if we perform below queries, we will get different results. If we use TOP 10, we will get below result:
SELECT TOP 10 [Id],[NDate] FROM [Test] order by NDate desc
RESULT=>
Id NDate
4 2011-08-24 00:00:00.000
3 2011-08-24 00:00:00.000
2 2011-08-24 00:00:00.000
1 2011-08-24 00:00:00.000
11 2011-08-21 00:00:00.000
10 2011-08-21 00:00:00.000
9 2011-08-21 00:00:00.000
8 2011-08-21 00:00:00.000
7 2011-08-21 00:00:00.000
6 2011-08-21 00:00:00.000
select id,NDate from (
select ROW_NUMBER() over (order by NDate DESC) as RNumber, Id,NDate
from Test) as t
where RNumber between 1 and 10
RESULT=>
id NDate
1 2011-08-24 00:00:00.000
2 2011-08-24 00:00:00.000
3 2011-08-24 00:00:00.000
4 2011-08-24 00:00:00.000
5 2011-08-21 00:00:00.000
6 2011-08-21 00:00:00.000
7 2011-08-21 00:00:00.000
8 2011-08-21 00:00:00.000
9 2011-08-21 00:00:00.000
10 2011-08-21 00:00:00.000
The issue is, When you are using LINQ to SQL, and you want to do pagination, generated query for selecting first page will be TOP X, while for the other pages will be using ROW_NUMBER, and the result is, some items will never appear in the listing.
You need to implement a secondary sorting.
Example:
select id,NDate from (
select ROW_NUMBER() over (order by NDate DESC, id) as RNumber, Id,NDate -- Note: NDate DESC, id
from Test) as t
where RNumber between 1 and 10
Example:
SELECT TOP 10 [Id],[NDate] FROM [Test] order by NDate desc, ID -- Note: NDate DESC, id
Otherwise, you might as well expect random records per unique NDate.
If you want the same records for each query, you have to specify that secondary sort column.
I agree with #hamlin11, but putting it more simply :-)
In the first example you are sorting by
order by NDate desc
/* to get same results as example 2, change this to
order by NDate desc, id
*/
and in the second by
order by NDate DESC, id
In the second example you are sorting by Id, that is why the ID column is in order, you haven't done this in the first example.
It might be better to use data like this, so you can see more clearly what is happening:
/****** Object: Table [dbo].[Test] Script Date: 08/27/2011 07:56:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Test](
[Id] [int] IDENTITY(1,1) NOT NULL,
[NDate] [datetime] NOT NULL,
CONSTRAINT [PK_Test] 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
SET IDENTITY_INSERT [dbo].[Test] ON
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (1, '2011-08-10 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (2, '2011-08-11 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (3, '2011-08-12 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (4, '2011-08-13 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (5, '2011-08-14 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (6, '2011-08-15 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (7, '2011-08-16 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (8, '2011-08-31 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (9, '2011-08-30 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (10, '2011-08-29 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (11, '2011-08-28 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (12, '2011-08-27 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (13, '2011-08-26 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (14, '2011-08-25 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (15, '2011-08-24 00:00:00.000')
INSERT [dbo].[Test] ([Id], [NDate]) VALUES (16, '2011-08-23 00:00:00.000')
SET IDENTITY_INSERT [dbo].[Test] OFF
Related
I have a table named tasks inside is
id
tasks
tasks_status
task_date
The tasks statuses are "done","pending","forwarded","cancelled".
How can I query the table of counting all the done, all the pending, all the forwarded and all cancelled.
I tried doing all the tweaks from COUNT but to no avail. It's been 2 hours of looking for a way. Please help
My goal is to specifically count only those DONE, I can get the count of all the specifics but just would need to show the total count of done (for example)
Group by is better but if you just want the ones specified as 'Done' the below should work.
SELECT COUNT(*) FROM TASTS WHERE TASKS_STATUS='done'
Select what you want with count and Group Them.
SELECTS tasks_status, count(tasks_status) FROM status GROUP BY tasks_status;
select tasks_status, count(*) from tasks group by tasks_status
http://sqlfiddle.com/#!17/1e27e/4/0
If you want to get all counts then you need to use group by but if you want to get count of just one item then group by is not required.
Following is query to generate scenario
CREATE TABLE [dbo].[tasks](
[id] [int] IDENTITY(1,1) NOT NULL,
[tasks] [varchar](50) NULL,
[tasks_status] [varchar](50) NULL,
[task_date] [date] NULL,
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
SET IDENTITY_INSERT [dbo].[tasks] ON
GO
INSERT [dbo].[tasks] ([id], [tasks], [tasks_status], [task_date]) VALUES (1, N'task1', N'pending', CAST(N'2022-09-30' AS Date))
GO
INSERT [dbo].[tasks] ([id], [tasks], [tasks_status], [task_date]) VALUES (2, N'task2', N'forwarded', CAST(N'2022-09-30' AS Date))
GO
INSERT [dbo].[tasks] ([id], [tasks], [tasks_status], [task_date]) VALUES (3, N'task3', N'pending', CAST(N'2022-09-30' AS Date))
GO
INSERT [dbo].[tasks] ([id], [tasks], [tasks_status], [task_date]) VALUES (4, N'task4', N'done', CAST(N'2022-09-30' AS Date))
GO
INSERT [dbo].[tasks] ([id], [tasks], [tasks_status], [task_date]) VALUES (5, N'task5', N'done', CAST(N'2022-09-30' AS Date))
GO
INSERT [dbo].[tasks] ([id], [tasks], [tasks_status], [task_date]) VALUES (6, N'task6', N'cancelled', CAST(N'2022-09-30' AS Date))
GO
INSERT [dbo].[tasks] ([id], [tasks], [tasks_status], [task_date]) VALUES (7, N'task7', N'done', CAST(N'2022-09-30' AS Date))
GO
INSERT [dbo].[tasks] ([id], [tasks], [tasks_status], [task_date]) VALUES (8, N'task8', N'forwarded', CAST(N'2022-09-30' AS Date))
GO
INSERT [dbo].[tasks] ([id], [tasks], [tasks_status], [task_date]) VALUES (9, N'task9', N'pending', CAST(N'2022-09-30' AS Date))
GO
INSERT [dbo].[tasks] ([id], [tasks], [tasks_status], [task_date]) VALUES (10, N'task10', N'done', CAST(N'2022-09-30' AS Date))
GO
SET IDENTITY_INSERT [dbo].[tasks] OFF
GO
You can use group by if you want to get count of all unique tasks_status or some of tasks_status using following query
For All
SELECT tasks_status, count(tasks_status) FROM dbo.tasks GROUP BY tasks_status;
For done and pending
SELECT tasks_status, count(tasks_status) FROM dbo.tasks
WHERE tasks_status IN ('done','pending')
GROUP BY tasks_status
if you want to get count for done only then you can use either of the following. Use group by if you want to use other columns in select, else if you want to get just count and no other column then just 2nd query without group by
SELECT tasks_status, count(tasks_status) FROM dbo.tasks
WHERE tasks_status = 'done'
GROUP BY tasks_status
or
SELECT COUNT(tasks_status) FROM dbo.tasks WHERE tasks_status='done'
I need to Calculate the Opening and closing Balance Transaction. I have Three Tables OB, Purchase, and Usage. The unique Key of all tables is Product id. I need a stored procedure for blow results. Based on the Product id selected need to calculate the opening and closing balance.
Table Structure: Below code contains Table and sample data
USE [BMC]
GO
/****** Object: Table [dbo].[TBLProductOB] Script Date: 08-07-2021 01:20:11 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TBLProductOB](
[Skey] [int] IDENTITY(1,1) NOT NULL,
[EntryDate] [date] NULL,
[Productid] [int] NULL,
[ProductOB] [decimal](12, 3) NULL,
CONSTRAINT [PK_TBLProductOB] PRIMARY KEY CLUSTERED
(
[Skey] 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
/****** Object: Table [dbo].[TBLProductPurchase] Script Date: 08-07-2021 01:20:11 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TBLProductPurchase](
[Skey] [int] IDENTITY(1,1) NOT NULL,
[Entrydate] [date] NULL,
[Productid] [int] NULL,
[P_Purchase] [decimal](12, 3) NULL,
CONSTRAINT [PK_TBLProductPurchase] PRIMARY KEY CLUSTERED
(
[Skey] 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
/****** Object: Table [dbo].[TBLProductUsage] Script Date: 08-07-2021 01:20:11 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TBLProductUsage](
[Skey] [int] IDENTITY(1,1) NOT NULL,
[Entrydate] [date] NULL,
[Productid] [int] NULL,
[P_Usage] [decimal](12, 3) NULL,
CONSTRAINT [PK_TBLProductUsage] PRIMARY KEY CLUSTERED
(
[Skey] 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
SET IDENTITY_INSERT [dbo].[TBLProductOB] ON
INSERT [dbo].[TBLProductOB] ([Skey], [EntryDate], [Productid], [ProductOB]) VALUES (4, CAST(N'2021-04-01' AS Date), 3, CAST(100.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductOB] ([Skey], [EntryDate], [Productid], [ProductOB]) VALUES (6, CAST(N'2021-04-01' AS Date), 1, CAST(10.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductOB] ([Skey], [EntryDate], [Productid], [ProductOB]) VALUES (7, CAST(N'2021-04-01' AS Date), 2, CAST(150.000 AS Decimal(12, 3)))
SET IDENTITY_INSERT [dbo].[TBLProductOB] OFF
SET IDENTITY_INSERT [dbo].[TBLProductPurchase] ON
INSERT [dbo].[TBLProductPurchase] ([Skey], [Entrydate], [Productid], [P_Purchase]) VALUES (1, CAST(N'2021-07-06' AS Date), 3, CAST(100.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductPurchase] ([Skey], [Entrydate], [Productid], [P_Purchase]) VALUES (7, CAST(N'2021-07-01' AS Date), 3, CAST(50.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductPurchase] ([Skey], [Entrydate], [Productid], [P_Purchase]) VALUES (8, CAST(N'2021-07-15' AS Date), 3, CAST(50.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductPurchase] ([Skey], [Entrydate], [Productid], [P_Purchase]) VALUES (9, CAST(N'2021-07-01' AS Date), 1, CAST(1.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductPurchase] ([Skey], [Entrydate], [Productid], [P_Purchase]) VALUES (10, CAST(N'2021-07-03' AS Date), 1, CAST(1.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductPurchase] ([Skey], [Entrydate], [Productid], [P_Purchase]) VALUES (11, CAST(N'2021-07-05' AS Date), 1, CAST(3.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductPurchase] ([Skey], [Entrydate], [Productid], [P_Purchase]) VALUES (12, CAST(N'2021-07-01' AS Date), 2, CAST(10.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductPurchase] ([Skey], [Entrydate], [Productid], [P_Purchase]) VALUES (13, CAST(N'2021-07-02' AS Date), 2, CAST(10.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductPurchase] ([Skey], [Entrydate], [Productid], [P_Purchase]) VALUES (14, CAST(N'2021-07-05' AS Date), 2, CAST(10.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductPurchase] ([Skey], [Entrydate], [Productid], [P_Purchase]) VALUES (15, CAST(N'2021-07-01' AS Date), 5, CAST(10.000 AS Decimal(12, 3)))
SET IDENTITY_INSERT [dbo].[TBLProductPurchase] OFF
SET IDENTITY_INSERT [dbo].[TBLProductUsage] ON
INSERT [dbo].[TBLProductUsage] ([Skey], [Entrydate], [Productid], [P_Usage]) VALUES (7, CAST(N'2021-07-01' AS Date), 3, CAST(10.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductUsage] ([Skey], [Entrydate], [Productid], [P_Usage]) VALUES (8, CAST(N'2021-07-02' AS Date), 3, CAST(10.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductUsage] ([Skey], [Entrydate], [Productid], [P_Usage]) VALUES (9, CAST(N'2021-07-08' AS Date), 3, CAST(10.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductUsage] ([Skey], [Entrydate], [Productid], [P_Usage]) VALUES (10, CAST(N'2021-07-15' AS Date), 3, CAST(30.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductUsage] ([Skey], [Entrydate], [Productid], [P_Usage]) VALUES (11, CAST(N'2021-07-01' AS Date), 2, CAST(2.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductUsage] ([Skey], [Entrydate], [Productid], [P_Usage]) VALUES (12, CAST(N'2021-07-02' AS Date), 2, CAST(2.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductUsage] ([Skey], [Entrydate], [Productid], [P_Usage]) VALUES (13, CAST(N'2021-07-03' AS Date), 2, CAST(2.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductUsage] ([Skey], [Entrydate], [Productid], [P_Usage]) VALUES (14, CAST(N'2021-07-05' AS Date), 2, CAST(2.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductUsage] ([Skey], [Entrydate], [Productid], [P_Usage]) VALUES (16, CAST(N'2021-07-01' AS Date), 1, CAST(2.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductUsage] ([Skey], [Entrydate], [Productid], [P_Usage]) VALUES (17, CAST(N'2021-07-03' AS Date), 1, CAST(3.000 AS Decimal(12, 3)))
INSERT [dbo].[TBLProductUsage] ([Skey], [Entrydate], [Productid], [P_Usage]) VALUES (18, CAST(N'2021-07-04' AS Date), 2, CAST(2.000 AS Decimal(12, 3)))
SET IDENTITY_INSERT [dbo].[TBLProductUsage] OFF
Just tried: I don't know how to write a stored procedure for transaction-based. I was simply getting all the table results with the help of union.
Declare #1stOpeningBalance decimal(12,3)= (select ProductOB from TBLProductOB where Productid=2)
Select a.Entrydate,a.Productid,Lag(((Sum(a.Ob)+sum(a.Purchase))-sum(a.Usage)),1,#1stOpeningBalance) over (order by Entrydate asc) as Ob, sum(a.Purchase) as Purchase,(Sum(a.Ob)+sum(a.Purchase)) as Total, Sum(a.Usage) as Usage, ((Sum(a.Ob)+sum(a.Purchase))-sum(a.Usage)) as Cb from
(
select Entrydate,Productid,0 as Ob,Sum(Isnull(P_Purchase,0.000)) as Purchase,0 as Usage from TBLProductPurchase
group by EntryDate,Productid
union all
select Entrydate,Productid,0 as Ob,0 as Purchase,Sum(Isnull(P_Usage,0.000)) as Usage from TBLProductUsage
group by EntryDate,Productid
) as a
where Entrydate between '2021-07-01' and '2021-07-05' and Productid=2
group by a.EntryDate,a.Productid
Required Output Result:
You can use LEAD or LAG function to do this
Make sure you have only one record for the entry date. If you have multiple entries on the same date, you have to use a unique key to order
Assumption: you can calculate the closing balance and only opening balance needed to calcuate and need a system starting opening balance
Create table #temp_TBL(EntryDate date,Purchase decimal(18,2),total decimal(18,2),Usage decimal(18,2), CB decimal(18,2))
Declare #1stOpeningBalance decimal(18,2)=150
Insert into #temp_TBL (EntryDate,Purchase,total,Usage,CB)
values
('2021-07-01',10,160,2,158),
('2021-07-02',10,168,2,166),
('2021-07-03',0,166,2,164),
('2021-07-04',0,164,2,162),
('2021-07-05',10,172,2,170)
select EntryDate
,Lag(CB,1,#1stOpeningBalance) over (order by EntryDate ASC) as OB
,Purchase,total,Usage,CB from #temp_TBL
Output
I have a question that I dont know If there is solution to in sql. Made an small example
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Events](
[Id] [int] IDENTITY(1,1) NOT NULL,
[EventTime] [datetime] NOT NULL,
[Event] [nvarchar](50) NOT NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Logging] Script Date: 2020-07-07 14:35:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Logging](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FromTime] [datetime] NOT NULL,
[ToTime] [datetime] NOT NULL,
[Status] [nvarchar](50) NULL
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Events] ON
GO
INSERT [dbo].[Events] ([Id], [EventTime], [Event]) VALUES (1, CAST(N'2020-07-07T14:14:00.000' AS DateTime), N'str')
GO
INSERT [dbo].[Events] ([Id], [EventTime], [Event]) VALUES (2, CAST(N'2020-07-07T07:01:00.000' AS DateTime), N'testcall')
GO
INSERT [dbo].[Events] ([Id], [EventTime], [Event]) VALUES (3, CAST(N'2020-07-07T15:22:00.000' AS DateTime), N'ipfail')
GO
SET IDENTITY_INSERT [dbo].[Events] OFF
GO
SET IDENTITY_INSERT [dbo].[Logging] ON
GO
INSERT [dbo].[Logging] ([Id], [FromTime], [ToTime], [Status]) VALUES (1, CAST(N'2020-07-07T01:00:00.000' AS DateTime), CAST(N'2020-07-07T13:00:00.000' AS DateTime), N'All well')
GO
INSERT [dbo].[Logging] ([Id], [FromTime], [ToTime], [Status]) VALUES (2, CAST(N'2020-07-07T13:01:00.000' AS DateTime), CAST(N'2020-07-07T15:00:00.000' AS DateTime), N'All well')
GO
INSERT [dbo].[Logging] ([Id], [FromTime], [ToTime], [Status]) VALUES (3, CAST(N'2020-07-07T15:33:00.000' AS DateTime), CAST(N'2020-07-07T20:00:00.000' AS DateTime), N'All well')
GO
INSERT [dbo].[Logging] ([Id], [FromTime], [ToTime], [Status]) VALUES (4, CAST(N'2020-07-07T20:01:00.000' AS DateTime), CAST(N'2020-07-07T23:00:00.000' AS DateTime), N'All well')
GO
SET IDENTITY_INSERT [dbo].[Logging] OFF
GO
When doing an inner join of this table I want to find the Event in Event table that doesn't have a matching timeframe in Logging. The timeframe that's missing is 15:00 to 15:33 and the event that happens that happens is the Event with ID 3. Everything is measured in minutes. Is this possible? Or have to do it some other way?
If I understand correctly, you want not exists:
select l.*
from logging l
where not exists (select 1
from events e
where e.eventtime >= l.fromtime and
e.eventtime <= l.totime
);
However, this returns two timeframes -- ones with ids 3 and 4.
Here is a db<>fiddle.
I need to write query for top three record(count and sum) for each branch of company and I have branch costumers and contracts tables
First of all, create a table like this:
CREATE TABLE [dbo].[Branches](
[Id] [int] NOT NULL,
[CompanyId] [int] NULL,
[Something] [int] NULL,
CONSTRAINT [PK_Table_5] 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
Then, insert some data into it:
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (1, 1, 10)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (2, 1, 15)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (3, 1, 20)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (4, 1, 25)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (5, 1, 22)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (6, 2, 50)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (7, 2, 32)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (8, 2, 30)
GO
INSERT [dbo].[Branches] ([Id], [CompanyId], [Something]) VALUES (9, 2, 10)
GO
In the end, your query will be like this:
SELECT result.Companyid, SUM(result.Something) [Sum], (SELECT COUNT(*) FROM Branches WHERE CompanyId = result.companyid) AS [Count]
FROM (
SELECT companyid, Something, Rank()
OVER (PARTITION BY CompanyId
ORDER BY id DESC ) AS Rank
FROM Branches
) result WHERE Rank <= 3
GROUP BY CompanyId
Schema:
First data:
Result:
I use SQL Server Management Studio with SQL Server 2016.
When I run this SQL statement, it doesn't return any values, even though the record is already there. Could you help please? What is the problem?
My query:
select *
from device_os
where name = '4.2 (Jelly Bean)'
This is the script for the table creation:
USE [my_database]
GO
/****** Object: Table [dbo].[device_os] Script Date: 08-Nov-17 3:49:11 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[device_os](
[id] [smallint] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NOT NULL,
CONSTRAINT [PK_device_os] 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
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[device_os] ON
INSERT [dbo].[device_os] ([id], [name]) VALUES (114, N'4.4.2')
INSERT [dbo].[device_os] ([id], [name]) VALUES (115, N'2.3.64.14.14.1')
INSERT [dbo].[device_os] ([id], [name]) VALUES (116, N'6.1.5')
INSERT [dbo].[device_os] ([id], [name]) VALUES (117, N'4.0.0')
INSERT [dbo].[device_os] ([id], [name]) VALUES (118, N'4.4.2 KOT49H.H1')
INSERT [dbo].[device_os] ([id], [name]) VALUES (119, N'unknown')
INSERT [dbo].[device_os] ([id], [name]) VALUES (120, N'CrunKeD! Galaxy Ace Ventura')
INSERT [dbo].[device_os] ([id], [name]) VALUES (121, N'7.0.5')
INSERT [dbo].[device_os] ([id], [name]) VALUES (122, N'7.0.6')
INSERT [dbo].[device_os] ([id], [name]) VALUES (123, N'6.1.6')
INSERT [dbo].[device_os] ([id], [name]) VALUES (124, N'4.4.2 (0Din Edition)')
INSERT [dbo].[device_os] ([id], [name]) VALUES (132, N'7.1.1')
INSERT [dbo].[device_os] ([id], [name]) VALUES (133, N'OS')
INSERT [dbo].[device_os] ([id], [name]) VALUES (134, N'4.2 (Jelly Bean)')
INSERT [dbo].[device_os] ([id], [name]) VALUES (135, N'5.0.0.1036')
INSERT [dbo].[device_os] ([id], [name]) VALUES (136, N'7.1.0.285')
INSERT [dbo].[device_os] ([id], [name]) VALUES (137, N'6.0.0.756')
INSERT [dbo].[device_os] ([id], [name]) VALUES (138, N'ICS Powered By PMP Engine')
INSERT [dbo].[device_os] ([id], [name]) VALUES (139, N'6.0.0.668')
SET IDENTITY_INSERT [dbo].[device_os] OFF
Screenshots for the problem :
select * without condition and the record is there 'highlighted in yellow'
When I add a condition on the value '4.2 (Jelly Bean)' no result there
The query at the top of your post should work:
select *
from device_os where
[name] = '4.2 (Jelly Bean)'
If it doesn't, you may have leading spaces. Note, trailing spaces usually doesn't matter for equality operators. Leading spaces do. If you think you may have them, try:
select *
from device_os
where ltrim([name]) = '4.2 (Jelly Bean)'
The only other thing it could be is you think you have a space in the name but you don't. Use this to see:
select *
from device_os
where ltrim([name]) = '4.2(Jelly Bean)' --space removed from between 2 and (
ONLINE DEMO
There are two spaces in there
'4.2 (Jelly Bean)'
Adding a separator to make it clear :
'4.2 | (Jelly Bean)'
Given this table :
declare #device_os table ([id] [smallint] NOT NULL,[name] [varchar](50) NOT NULL)
INSERT #device_os ([id], [name])
VALUES
(114, N'4.4.2'),
(115, N'2.3.64.14.14.1'),
(116, N'6.1.5'),
(117, N'4.0.0'),
(118, N'4.4.2 KOT49H.H1'),
(119, N'unknown'),
(120, N'CrunKeD! Galaxy Ace Ventura'),
(121, N'7.0.5'),
(122, N'7.0.6'),
(123, N'6.1.6'),
(124, N'4.4.2 (0Din Edition)'),
(132, N'7.1.1'),
(133, N'OS'),
(134, N'4.2 (Jelly Bean)'),
(135, N'5.0.0.1036'),
(136, N'7.1.0.285'),
(137, N'6.0.0.756'),
(138, N'ICS Powered By PMP Engine'),
(139, N'6.0.0.668')
The original query won't return anything:
select * from #device_os
where name = '4.2 (Jelly Bean)'
id name
--- -----------------
Using two spaces between 4.2 and Jelly Bean though will return the record:
select * from #device_os
where name = '4.2 (Jelly Bean)'
id name
--- -----------------
134 4.2 (Jelly Bean)
I found the root cause of the problem after much trials.
It looks like special characters were inserted when the data was initially inserted and it is not appear in the SSMS. I did the following:-
update this record in the database table:-
update device_os set name='4.2 (Jelly Bean)' where id=134
Run the same select statement again:-
select *
from device_os where
[name] = '4.2 (Jelly Bean)'
Now, it is working...
Thanks every body...