Excluding rows from second table but including in comparison - sql

I have two tables with the same data in it I need to compare one column here is the ddl for testing
USE [DifferencesDB]
GO
/****** Object: Table [dbo].[FirstTable] Script Date: 11/06/2019 15:27:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FirstTable](
[Id] [int] NULL,
[Column1] [nchar](10) NULL,
[Column2] [nchar](10) NULL,
[Column4] [decimal](18, 0) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[FirstTable] ([Id], [Column1], [Column2], [Column4]) VALUES (1, N'test ', N'test ', 30)
GO
INSERT [dbo].[FirstTable] ([Id], [Column1], [Column2], [Column4]) VALUES (2, N'test2 ', N'test3 ', 18)
GO
CREATE TABLE [dbo].[SecondTable](
[Id] [int] NULL,
[Column1] [nchar](10) NULL,
[Column2] [nchar](10) NULL,
[Column4] [decimal](18, 5) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[SecondTable] ([Id], [Column1], [Column2], [Column4]) VALUES (1, N'test ', N'test ', 13.56895)
GO
INSERT [dbo].[SecondTable] ([Id], [Column1], [Column2], [Column4]) VALUES (2, N'test2 ', N'test3 ', 18.456 )
GO
As you can see here what I want to do is compare to the two tables and the Data in Column 4 which is a decimal.
/****** Script for SelectTopNRows command from SSMS ******/
SELECT ABS(T0.Column4 -T1.Column4) as 'Difference'
FROM [FirstTable] T0, [SecondTable] T1
where T0.Id =T1.ID
This works but it gives me back tones of extra rows this gets me the difference I require so how do I exclude the rows from the other table.
So, for example, it should say the difference is I would like the data to be returned from the second table but also the difference column as well.
.456
Edit
TO show what is happening on live data.
Please see my new query here
SELECT GoodData_Lines.Qty,
Invalid_Lines.Qty,
abs(GoodData_Lines.Qty- Invalid_Lines.Qty) AS 'Difference'
FROM GoodData_Lines
left OUTER JOIN Invalid_MCSSOPLines
ON GoodData_Lines.LineID = Invalid_Lines.LineID

Not exactly sure what the question was, but based on how I understand it, will this do?
SELECT T1.*, ABS(T0.Column4 -T1.Column4) as 'Difference'
FROM [FirstTable] T0 right join [SecondTable] T1
on T0.Id =T1.ID

This can be a solution?
[EDIT] following your update
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[GoodData_Lines](
[LineID] [int] NULL,
[Column1] [nchar](10) NULL,
[Column2] [nchar](10) NULL,
[Qty] [decimal](18, 0) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[GoodData_Lines] ([LineID], [Column1], [Column2], [Qty]) VALUES (1, N'test ', N'test ', 30)
GO
INSERT [dbo].[GoodData_Lines] ([LineID], [Column1], [Column2], [Qty]) VALUES (2, N'test2 ', N'test3 ', 18)
GO
CREATE TABLE [dbo].[Invalid_MCSSOPLines](
[LineID] [int] NULL,
[Column1] [nchar](10) NULL,
[Column2] [nchar](10) NULL,
[Qty] [decimal](18, 5) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[Invalid_MCSSOPLines] ([LineID], [Column1], [Column2], [Qty]) VALUES (1, N'test ', N'test ', 13.56895)
GO
INSERT [dbo].[Invalid_MCSSOPLines] ([LineID], [Column1], [Column2], [Qty]) VALUES (2, N'test2 ', N'test3 ', 18.456 )
GO
SELECT GoodData_Lines.Qty,
isnull( [Invalid_MCSSOPLines].Qty,0) invalid_qty,
abs(GoodData_Lines.Qty - isnull([Invalid_MCSSOPLines].Qty,0)) AS 'Difference'
FROM GoodData_Lines
left OUTER JOIN Invalid_MCSSOPLines
ON GoodData_Lines.LineID = [Invalid_MCSSOPLines].LineID
-- eventually drop table if no more needed
-- DROP TABLE [GoodData_Lines]
-- DROP TABLE [Invalid_MCSSOPLines]

Related

How to solve error Conversion failed when converting the nvarchar value to data type integer?

I work on SQL Server 2014 with a dynamic query; I get this error when I run the query:
Conversion failed when converting the nvarchar value '24VAC/DC' to data type int.
I got error when executing this dynamic SQL
EXEC (#SQL)
How to solve this error please?
Data sample
IF OBJECT_ID('dbo.TAllfeatures') IS NOT NULL
DROP TABLE dbo.TAllfeatures
IF OBJECT_ID('dbo.TCondition') IS NOT NULL
DROP TABLE dbo.TCondition
IF OBJECT_ID('dbo.TPartAttributes') IS NOT NULL
DROP TABLE dbo.TPartAttributes
IF OBJECT_ID('dbo.TAllData') IS NOT NULL
DROP TABLE dbo.TAllData
CREATE TABLE [dbo].[TAllfeatures]
(
[ZPLID] [int] NULL,
[ZfeatureKey] [bigint] NULL,
[FeatType] [int] NULL,
[AcceptedValueID] [int] NULL,
[IsNumericValues] [int] NULL
) ON [PRIMARY]
GO
INSERT INTO [dbo].[TAllfeatures] ([ZPLID], [ZfeatureKey], [FeatType], [AcceptedValueID], [IsNumericValues])
VALUES (75533, NULL, 0, 0, 0)
INSERT INTO [dbo].[TAllfeatures] ([ZPLID], [ZfeatureKey], [FeatType], [AcceptedValueID], [IsNumericValues])
VALUES (75533, 1505730001, 2044, 155, 0)
INSERT INTO [dbo].[TAllfeatures] ([ZPLID], [ZfeatureKey], [FeatType], [AcceptedValueID], [IsNumericValues])
VALUES (75533, 1505730011, 2044, 274, 1)
INSERT INTO [dbo].[TAllfeatures] ([ZPLID], [ZfeatureKey], [FeatType], [AcceptedValueID], [IsNumericValues])
VALUES (75533, 1505730036, 2044, 271, 0)
CREATE TABLE [dbo].[TCondition]
(
[TradeCodeControlID] [int] NOT NULL,
[VersionYear] [int] NULL,
[Version] [float] NULL,
[CodeTypeID] [int] NULL,
[RevisionID] [bigint] NULL,
[Code] [varchar](20) NULL,
[ZPLID] [int] NULL,
[ZfeatureKey] [bigint] NULL,
[ZfeatureType] [nvarchar](200) NULL,
[EStrat] [nvarchar](2500) NULL,
[EEnd] [nvarchar](2500) NULL
) ON [PRIMARY]
INSERT INTO [dbo].[TCondition] ([TradeCodeControlID], [VersionYear], [Version], [CodeTypeID], [RevisionID], [Code], [ZPLID], [ZfeatureKey], [ZfeatureType], [EStrat], [EEnd])
VALUES (8123, 2020, 26, 849774, 307683692, N'8535400000', 75533, 1505730001, NULL, N'In(''Surge Protector'',''Surge Protector for Media Lines Only'',''Outlet Strip, Surge Protector'',''PDU, Surge Protector'',''Surge Lightning Arrester'',''Surge Arrester'',''Surge Protection Module'',''Lightning Arrester'',''Lightning Current Arrester'',''Protection Device'',''Surge Voltage Equipment'',''Isolated'',''Surge Protection'',''Coaxial'',''Base Element'')', N'')
INSERT INTO [dbo].[TCondition] ([TradeCodeControlID], [VersionYear], [Version], [CodeTypeID], [RevisionID], [Code], [ZPLID], [ZfeatureKey], [ZfeatureType], [EStrat], [EEnd])
VALUES (8124, 2020, 26, 849774, 307683692, N'8535400000', 75533, 1505730036, NULL, N'>1000', N'')
CREATE TABLE [dbo].[TPartAttributes]
(
[PartID] [int] NOT NULL,
[ZfeatureKey] [bigint] NULL,
[AcceptedValuesOption_Value] [float] NULL,
[Name] [nvarchar](500) NOT NULL
) ON [PRIMARY]
GO
INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (1128078, 1505730036, 24, N'24VAC/DC')
INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (1128078, 1505730001, NULL, N'Surge Voltage Equipment')
INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (1128089, 1505730036, 5, N'5V')
INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (1128089, 1505730001, NULL, N'Attachment Plug')
INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (27912821, 1505730001, NULL, N'Surge Protection Module')
INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (27912821, 1505730036, 480, N'480V')
INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (32817870, 1505730001, NULL, N'Surge Protector')
INSERT INTO [dbo].[TPartAttributes] ([PartID], [ZfeatureKey], [AcceptedValuesOption_Value], [Name])
VALUES (32817870, 1505730036, NULL, N'120V, 240V')
CREATE TABLE dbo.TAllData
(
PartID INT,
Code VARCHAR(20),
CodeTypeID INT,
RevisionID BIGINT,
ZPLID INT,
ConCount INT
)
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
DECLARE #ConStr nvarchar(max) = STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ', CC.ZfeatureKey , IIF(CC.ZfeatureType='Qualifications',' And AcceptedValuesOption_Value ' , ' And Name ' ) , CAST(EStrat AS NVARCHAR(2500)),')') --ValueName
FROM dbo.TCondition CC INNER JOIN dbo.TAllfeatures AL with(nolock) ON AL.ZfeatureKey = CC.ZfeatureKey AND AL.IsNumericValues =0
FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'')
DECLARE #Sql nvarchar(max)= CONCAT('INSERT INTO dbo.TAllData(PartID,Code,CodeTypeID,RevisionID,ZPLID ,ConCount)',' SELECT PartID,Code,Co.CodeTypeID,Co.RevisionID,Co.ZPLID,Count(1) as ConCount
FROM
dbo.TPartAttributes PM with(nolock)
INNER JOIN dbo.TCondition Co with(nolock) ON Co.ZfeatureKey = PM.ZfeatureKey ',
'Where (1=1 and ' , #ConStr,' ) Group By PartID,Code,Co.CodeTypeID,Co.RevisionID,Co.ZPLID ' ,
' Having Count(1)>= ',(SELECT COUNT(1) FROM TCondition with(nolock)))
--print #SQL
EXEC (#SQL)
I try to solve issue but still issue exist
DECLARE #ConStr nvarchar(max)= STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ''', CC.ZfeatureKey , '''', IIF(CC.ZfeatureType='Qualifications',' And AcceptedValuesOption_Value ' , ' And Name ' ) , LEFT(EStrat, 1), '''', SUBSTRING(EStrat, 2, LEN(EStrat) -1), ''')') --ValueName
FROM dbo.TCondition CC INNER JOIN dbo.TAllfeatures AL ON AL.ZfeatureKey = CC.ZfeatureKey AND AL.IsNumericValues =0
FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'')
It appears you do not need dynamic SQL at all here.
It's hard to know what logic you are trying to achieve, owing to a lack of sample data and expected output, and your existing query could do with better formatting. But it looks like it's some kind of relational division.
Note that you should not use WITH (NOLOCK) unless you really know what you are doing. It can give wildly incorrect results.
I also strongly suggest you use table references on each column, especially within subqueries
INSERT INTO dbo.TAllData
(PartID, Code, CodeTypeID, RevisionID, ZPLID, ConCount)
SELECT
PartID,
Code,
Co.CodeTypeID,
Co.RevisionID,
Co.ZPLID,
Count(1) as ConCount
FROM dbo.TPartAttributes PM
INNER JOIN dbo.TCondition Co ON Co.ZfeatureKey = PM.ZfeatureKey
Where EXISTS (SELECT 1
FROM dbo.TAllfeatures AL
WHERE AL.ZfeatureKey = Co.ZfeatureKey
AND AL.IsNumericValues = 0
AND IIF(Co.ZfeatureType = 'Qualifications', AcceptedValuesOption_Value, Name) = EStrat
)
Group By
PartID,
Code,
Co.CodeTypeID,
Co.RevisionID,
Co.ZPLID
Having Count(1) >= (SELECT COUNT(1) FROM TCondition);

Find non existing time intervall when doing join to another table

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.

Generate missing rows using JOIN / CROSS JOIN

I have 3 tables which are used to fill dynamic from value.
The table is represented by schema below.
User can add as many rows as possible, and the rows are shown to end user by template from FormField table.
The data that is saved in FormValues are only for not null values and any values that missing are not saved.
Now the problem is I have to generate report as expected below.
I have tried various combination of join / cross join, but none of them works as expected.
I am able to achieve this in C# via loops, but not able to do the same via SQL Server.
Script attached for DB
USE [SampleDb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FormTemplate](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_FormTemplate] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
) ON [PRIMARY]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FormField](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FormId] [int] NOT NULL,
[FieldName] [nvarchar](50) NULL,
[FieldType] [nvarchar](50) NULL,
CONSTRAINT [PK_FormField] PRIMARY KEY CLUSTERED
(
[Id] ASC
)
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[FormTemplate] Script Date: 3/2/2020 10:10:22 PM ******/
/****** Object: Table [dbo].[FormValue] Script Date: 3/2/2020 10:10:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[FormValue](
[FormId] [int] NOT NULL,
[FieldId] [int] NOT NULL,
[RowIndex] [int] NOT NULL,
[FormValue] [nvarchar](50) NULL,
CONSTRAINT [PK_FormValue] PRIMARY KEY CLUSTERED
(
[FormId] ASC,
[FieldId] ASC,
[RowIndex] ASC
)
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[FormField] ON
GO
INSERT [dbo].[FormField] ([Id], [FormId], [FieldName], [FieldType]) VALUES (1, 1, N'FirstName', N'string')
GO
INSERT [dbo].[FormField] ([Id], [FormId], [FieldName], [FieldType]) VALUES (2, 1, N'LastName', N'string')
GO
INSERT [dbo].[FormField] ([Id], [FormId], [FieldName], [FieldType]) VALUES (3, 1, N'Place', N'string')
GO
INSERT [dbo].[FormField] ([Id], [FormId], [FieldName], [FieldType]) VALUES (4, 1, N'age', N'int')
GO
INSERT [dbo].[FormField] ([Id], [FormId], [FieldName], [FieldType]) VALUES (5, 1, N'dob', N'date')
GO
SET IDENTITY_INSERT [dbo].[FormField] OFF
GO
SET IDENTITY_INSERT [dbo].[FormTemplate] ON
GO
INSERT [dbo].[FormTemplate] ([Id], [Name]) VALUES (1, N'Sample')
GO
SET IDENTITY_INSERT [dbo].[FormTemplate] OFF
GO
INSERT [dbo].[FormValue] ([FormId], [FieldId], [RowIndex], [FormValue]) VALUES (1, 1, 1, N'fname1')
GO
INSERT [dbo].[FormValue] ([FormId], [FieldId], [RowIndex], [FormValue]) VALUES (1, 2, 1, N'lname1')
GO
INSERT [dbo].[FormValue] ([FormId], [FieldId], [RowIndex], [FormValue]) VALUES (1, 2, 3, N'lname3')
GO
INSERT [dbo].[FormValue] ([FormId], [FieldId], [RowIndex], [FormValue]) VALUES (1, 4, 5, N'20')
GO
INSERT [dbo].[FormValue] ([FormId], [FieldId], [RowIndex], [FormValue]) VALUES (1, 5, 3, N'10/10/2020')
GO
This answers the original version of the question -- and then some. But I don't update answers to conform to evolving questions.
You seem to want cross joins on three "tables". The third needs to generate the rowindex values:
select f.id as formtemplateid, ff.id as formfieldid, v.rowindex,
fv.value
from formtemplate f cross join
formfield ff cross join
(values (1), (2), (3), (4), (5)) v(rowindex) left join
formvalues fv
on fv.formtemplateid = f.id and
fv.formfieldid = ff.id and
fv.rowindex = v.rowindex
order by f.id, ff.id, v.rowindex;
EDIT:
You can generate up to 100 numbers using a recursive CTE by doing:
with n as (
select 1 as n
union all
select n + 1
from n
where n < 10 -- "10" is however many you want
)
select n.n
from n;

Get 'balanced' column value as 'Y' if both rows has same amt and 'N' if not in SQL query

I have number of CR records and DR records against the same id ,
I need to check sum of DR amount matches with the sum of CR amount for the same id if CR matches with DR then display Balanced column as "Y" else "N"
Required Result: Balanced" column value 'Y' if the Credit and Debit amt column matches and 'N' if they mismatch
Note: single query is needed for this:
As shown in above screen grab red highlighted result is required .
Script is given below :
USE [data]
GO
/****** Object: Table [dbo].[BankData] Script Date: 04-05-2018 3.54.46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[BankData](
[ID] [int] NOT NULL,
[Name] [nchar](10) NULL,
[Amt] [decimal](18, 0) NULL,
[Type] [char](10) NULL,
[TransId] [int] IDENTITY(1,1) NOT NULL,
[CustId] [int] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Customer] Script Date: 04-05-2018 3.54.46 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customer](
[CustId] [int] NULL,
[Address] [nvarchar](50) NULL
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[BankData] ON
INSERT [dbo].[BankData] ([ID], [Name], [Amt], [Type], [TransId], [CustId]) VALUES (1, N'YASH ', CAST(300 AS Decimal(18, 0)), N'DR ', 1, 1)
INSERT [dbo].[BankData] ([ID], [Name], [Amt], [Type], [TransId], [CustId]) VALUES (1, N'YASH ', CAST(300 AS Decimal(18, 0)), N'CR ', 2, 1)
INSERT [dbo].[BankData] ([ID], [Name], [Amt], [Type], [TransId], [CustId]) VALUES (2, N'FALE ', CAST(120 AS Decimal(18, 0)), N'DR ', 3, 2)
INSERT [dbo].[BankData] ([ID], [Name], [Amt], [Type], [TransId], [CustId]) VALUES (2, N'FALE ', CAST(140 AS Decimal(18, 0)), N'CR ', 4, 2)
INSERT [dbo].[BankData] ([ID], [Name], [Amt], [Type], [TransId], [CustId]) VALUES (3, N'RAHUL ', CAST(100 AS Decimal(18, 0)), N'CR ', 5, 3)
INSERT [dbo].[BankData] ([ID], [Name], [Amt], [Type], [TransId], [CustId]) VALUES (3, N'RAHUL ', CAST(100 AS Decimal(18, 0)), N'DR ', 6, 3)
INSERT [dbo].[BankData] ([ID], [Name], [Amt], [Type], [TransId], [CustId]) VALUES (4, N'DINESH ', CAST(900 AS Decimal(18, 0)), N'CR ', 7, 4)
INSERT [dbo].[BankData] ([ID], [Name], [Amt], [Type], [TransId], [CustId]) VALUES (4, N'DINESH ', CAST(900 AS Decimal(18, 0)), N'DR ', 8, 4)
INSERT [dbo].[BankData] ([ID], [Name], [Amt], [Type], [TransId], [CustId]) VALUES (2, N'FALE ', CAST(30 AS Decimal(18, 0)), N'DR ', 9, 2)
INSERT [dbo].[BankData] ([ID], [Name], [Amt], [Type], [TransId], [CustId]) VALUES (2, N'FALE ', CAST(130 AS Decimal(18, 0)), N'DR ', 10, 2)
SET IDENTITY_INSERT [dbo].[BankData] OFF
INSERT [dbo].[Customer] ([CustId], [Address]) VALUES (1, N'Mumbai')
INSERT [dbo].[Customer] ([CustId], [Address]) VALUES (2, N'Delhi')
INSERT [dbo].[Customer] ([CustId], [Address]) VALUES (3, N'Pune')
INSERT [dbo].[Customer] ([CustId], [Address]) VALUES (4, N'Banglore')
INSERT [dbo].[Customer] ([CustId], [Address]) VALUES (5, N'Surat')
If 2012+, this is a small matter using the window function sum() over
Example
Select *
,Balanced = IIF(sum(Amt * IIF([Type]='CR',-1,1)) over (Partition By ID) =0,'Y','N')
from [BankData]
Returns
ID Name Amt Type TransId CustId Balanced
1 YASH 300 DR 1 1 Y
1 YASH 300 CR 2 1 Y
2 FALE 120 DR 3 2 N
2 FALE 140 CR 4 2 N
2 FALE 30 DR 9 2 N
2 FALE 130 DR 10 2 N
3 RAHUL 100 CR 5 3 Y
3 RAHUL 100 DR 6 3 Y
4 DINESH 900 CR 7 4 Y
4 DINESH 900 DR 8 4 Y
I use in-query to get the Balanced column. I group by ID then get the sum of Amt. If type is CR then it is negative (-1*Amt) and if DR it is positive. Then I did a query for table bankData and assign it to it's own ID (t1.ID=t.ID). If sum is zero then it is balanced='Y' else it is not ('N').
select [ID], [Name], [Amt], [Type], [TransId], [CustId],
(select case when sum(case when [Type]='DR' then [Amt] else -1*[Amt] end)=0
then 'Y'
else 'N' end
from [dbo].[BankData] as t1
where t1.[ID] = t.[ID]
group by t1.[ID]) as Balanced
from [dbo].[BankData] as t
order by t.[ID], t.[TransId]

how to get table from first table when data is not there in second table

i have requirement where i need to show data of both tables when both the ID's are same.when id is present in first table and not there in second table i need to show data from first table
CREATE TABLE [dbo].[TEST](
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Status] [char](1) NULL,
[CreatedDate] [datetime] NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[Test_History](
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Status] [char](1) NULL,
[CreatedDate] [datetime] NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Test_History] Script Date: 06/19/2015 19:01:49 ******/
INSERT [dbo].[Test_History] ([ID], [Name], [Status], [CreatedDate]) VALUES (1, N'Mohan', N'A', CAST(0x0000A4BC01347E88 AS DateTime))
INSERT [dbo].[Test_History] ([ID], [Name], [Status], [CreatedDate]) VALUES (1, N'Mohan', N'I', CAST(0x0000A4BC0134A390 AS DateTime))
INSERT [dbo].[Test_History] ([ID], [Name], [Status], [CreatedDate]) VALUES (2, N'Rohan', N'A', CAST(0x0000A4BC01391FCC AS DateTime))
/****** Object: Table [dbo].[TEST] Script Date: 06/19/2015 19:01:49 ******/
INSERT [dbo].[TEST] ([ID], [Name], [Status], [CreatedDate]) VALUES (2, N'Rohan', N'I', CAST(0x0000A4BC0138D584 AS DateTime))
INSERT [dbo].[TEST] ([ID], [Name], [Status], [CreatedDate]) VALUES (1, N'Mohan', N'A', CAST(0x0000A4BC013072DC AS DateTime))
INSERT [dbo].[TEST] ([ID], [Name], [Status], [CreatedDate]) VALUES (3, N'Raj', N'A', CAST(0x0000A4BC0138DED7 AS DateTime))
INSERT [dbo].[TEST] ([ID], [Name], [Status], [CreatedDate]) VALUES (4, N'Krishna', N'A', CAST(0x0000A4BC0138EE31 AS DateTime))
so far i have tried my query to achieve the result
select T.ID,COALESCE(T.ID,TT.ID),T.Name,COALESCE(T.Name,TT.Name),T.status,COALESCE(T.status,TT.status)
from Test T LEFT JOIN (Select TOP 1 ID,MIN(Name)name,Status from Test_History
GROUP BY ID,status
)TT
ON T.ID = TT.ID
where T.ID = 3
Id = 1 and 2 present show i will get data from both tables
Id = 3 and 4 not present in the table
so using coalesce i will get the data
from first table and show in 2nd table column also
but is there any other way like both tables are same structure
i'm thinking of
Declare #tablename varchar(10)
IF EXISTS (SELECT 1 from TESt where id = #id)
IF COunt there in both tables
SET #tablename = Test
ELSE
SET #tablename = Test_history
select * from #tablename where id = #ID
can i get any solution like this
You can use EXCEPT.
Here is an example:
SELECT a,b
FROM (
VALUES (1, 2), (3, 4), (5, 6), (7, 8), (9, 10)
) AS MyTable(a, b)
EXCEPT
SELECT a,b
FROM (
VALUES (1, 2), (7, 8), (9, 10)
) AS MyTable(a, b);
This will return all rows of the upper statement, which are not in the second statement.
First: Thanks for the excellent setup for the data related to the question!
If your real question was if table variables can be used as described in your question, the answer is no; or more accurately that its not worth it.
Not recommended:
declare #TableName TABLE (
[ID] [int] NULL,
[Name] [varchar](10) NULL,
[Status] [char](1) NULL,
[CreatedDate] [datetime] NULL)
IF EXISTS (SELECT 1 from TESt where id = #id)
INSERT INTO #TableName SELECT * FROM dbo.TEST WHERE ID = #ID
ELSE INSERT INTO #TableName SELECT * FROM dbo.[Test_History] WHERE ID = #ID
select * from #tablename where id = #ID
Here's the solution I prefer:
DECLARE #ID INT = 3;
SELECT * FROM [dbo].[TEST] ss WHERE ss.id = #id
UNION ALL SELECT * FROM [dbo].[Test_History] th WHERE th.id = #id
and not exists ( SELECT * FROM [dbo].[TEST] ss WHERE ss.id = #id);
UNION ALL performs surprisingly well - don't forget the ALL keyword, and I am assuming that ID is a PK or AK.
If I'm understanding correctly and you want to display all records that match between the two tables and only records from first table when the id does not exist in the second in the same result set, then all you need is a simple left join:
SELECT *
FROM dbo.test t
LEFT OUTER JOIN Test_History th
ON t.id = th.id
WHERE t.id = #id