value comparison on sql server 2008 - sql-server

There is a table of 5 columns :
col1,col2,col3,col4,monthName
Something like:
col1 | col2 | col3 | col4 | monthName
----------------------------------------
4 | 5 | 55 | 8 | January
4 | 4 | 33 | 6 | February
col1 and col2 sum must be same as col4 of the last month. So i can compare it like
select * from table1 where col1+col2=col4 where monthName='February'
but it will compare all the rows wheres i want it to be month specific something like
select *
from table1
where col1+col2 = (select col4 from table1 where monthName='January')
where monthName='February'
How i do this in correct way?
Well, It is something about monthly report.
Perhaps my main problem is getting col4 from the past month(such as january).
I am trying to explain it more clearly:
Get the col1 and col2 of current month(Which is in the monthName column) and do the sum.
Get the col4 cells value from last month. In this case it is February of monthName column.
Compare the col1+col2(Current month) to col4 (Last month in monthName).
In my first example , the row number 2 is true because 4+4=8 which is getting matched with col4 value(8) of January. If col1 and col2 sum of current month match with last month's col4 data then users are good.
I can get col1 and col2 very easily:
select sum(col1+col2) as currentTotal from table1 where monthName='February'
But how i get the col4 value from last month and store it somewhere then compare to currentTotal? Every month there will be 15 rows inserted and will be compared to last month.
Not sure if this time i explained a little better!

The month naming is dubious, but with the information we have, the following should do the trick:
-- Creating a table variable as a sample for your query.
DECLARE #T TABLE (col1 INT, col2 INT, col3 INT, col4 INT, monthName VARCHAR(25))
INSERT INTO #T VALUES (4,4,55,9,'January'),(5,4,3,6,'February'), (3,3,3,6,'March')
-- Update the references to your actual table in this query.
;WITH CTE AS (SELECT *
, DATEPART(MM,monthName+' 01 2014') Mnum
FROM #T)
SELECT CA.*
FROM CTE C
CROSS APPLY
(SELECT col1, col2, col3, col4, monthName
FROM CTE B
WHERE B.Mnum-1 = C.Mnum AND (B.col1+B.col2 = C.col4)) CA
ORDER BY Mnum
What it does, is it assigns a number for the monthname, then uses that set in order of month numbers, and with CROSS APPLY selects only rows where the sum of col1 and 2 amount to the col4 of previous month number.

You can try something like the pseudo code below
select *
from table1 t1
join
(
select monthName, SUM(col1+col2-col4) as isZero
group by monthName
) as t2
on t2.monthName = t1.monthName
where t2.isZero != 0

Related

Count of col1 over order by col2

create table t (col1 int,col2 varchar(10))
insert into t values(10,'val')
insert into t values(20,null)
insert into t values(10,'val3')
insert into t values(40,'val1')
insert into t values(50,null)
insert into t values(60,'val')
--1.
SELECT *,COUNT(COL2) OVER (ORDER BY COL1) FROM T
--2.
SELECT *,COUNT(COL1) OVER (ORDER BY COL2) FROM T
I am not able to understand the output of two select query mentioned above.. can anybody elaborate.
The count column will contain the accumilative number of values in col2 that are not null, sorted by the value of col 1
SELECT *,COUNT(COL2) OVER (ORDER BY COL1) AS [count]
FROM T
ORDER BY COL1
Results:
col1 col2 count --explanation
10 val3 2 --The first two values of col1 are the same, and the values of col2 are not null.
10 val 2 --The first two values of col1 are the same, and the values of col2 are not null.
20 NULL 2 --A new value of col1, but col2 is null so it's not counted.
40 val1 3 --A new value of col1, and col2 is not null.
50 NULL 3 --A new value of col1, but col2 is null so it's not counted.
60 val 4 --A new value of col1, and col2 is not null.
Basically the same, just reverse the columns:
SELECT *,COUNT(COL1) OVER (ORDER BY COL2) As col1Count
FROM T
ORDER BY COL2
Results:
col1 col2 col1Count --explanation
20 NULL 2 --The first two values of col2 are the same (both null), and the values of col1 are not null.
50 NULL 2 --The first two values of col2 are the same (both null), and the values of col1 are not null.
60 val 4 --The next two values of col2 are the same (both 'val'), and the values of col1 are not null.
10 val 4 --The next two values of col2 are the same (both 'val'), and the values of col1 are not null.
40 val1 5 --A new value of col2, and col1 is not null.
10 val3 6 --A new value of col2, and col1 is not null.

Check if we have matching data for two columns inside a group

I have some data like:
ID Col1 Col2
--- ----- -----
5 10 10 <--- Matching
5 11 10
5 15 10
6 22 22 <--- Matching
6 10 22
6 12 22
And I tried a query like:
SELECT ID FROM #Table
GROUP BY ID HAVING MAX(COL1) = MAX(COL2)
But, this only returns id 6, as max for group 5 Col1 is 15 which does not match with Col2 max value 10 for group 5. Is there any way to get all groups 5 & 6 which has matching data 10 & 22 in Col1 & Col2?
Expected Output:
ID
---
5
6
Just showing the ID of matching group.
It is as smiple as this:
DECLARE #tblQuestion AS Table
(
ID int,
col1 int,
col2 int
)
INSERT INTO #tblQuestion VALUES
(5,10,10),
(5,11,10),
(5,15,10),
(6,22,22),
(6,10,22),
(6,12,22);
select distinct ID from #tblQuestion a
where a.col1 = a.col2
TRY THIS:
SELECT DISTINCT ID
FROM table_name
WHERE (col1 - col2) = 0
Try the below query. Maybe it is your requirement, first get same value rows and then get max value from group:
DECLARE #tblQuestion AS Table
(
ID INT,
Col1 INt,
Col2 INT
)
INSERT INTO #tblQuestion VALUES(5,10,10)
INSERT INTO #tblQuestion VALUES(5,10,21)
INSERT INTO #tblQuestion VALUES(5,27,10)
INSERT INTO #tblQuestion VALUES(6,10,12)
INSERT INTO #tblQuestion VALUES(6,15,15)
INSERT INTO #tblQuestion VALUES(6,25,25)
INSERT INTO #tblQuestion VALUES(6,18,10)
;WITH T AS
(
SELECT
*,
ROW_NUMBER() OVER (Partition BY ID order by Col1 Desc) AS PartNo
FROM #tblQuestion
WHERE Col1=Col2
)
SELECT ID,Col1,Col2 FROM T
WHERE PartNo=1
ORDER BY ID, Col1 DESC
Output:
Try this:
SELECT distinct ID FROM table_name
where COL1 = COL2
In my case I tried a different approach, as I needed to use GROUP BY & HAVING clause due to my original query complexity like:
SELECT DISTINCT ID FROM #Table
GROUP BY ID
HAVING MAX(CASE WHEN Col1 = Col2 THEN 1 ELSE 0 END) = 1
Just wanted to share my solution here, in case anyone is interested.

SQL Table to SQL Table

I have a database table in the following format (populated via .net function, empties are blank, not NULL):
A B C D
Spoons ID
38483
Date Amt Value Type
1/1/2017 2 12 Plastic
1/2/2017 4 30 Silver
1/3/2017 1 9 Wood
How can I write a stored procedure that will result in the following table?
Col1 Col2 Col3 Col4 Col5
----------------------------------------------------
Spoons 38483 1/1/2017 2 Plastic
Spoons 38483 1/2/2017 4 Silver
Spoons 38483 1/3/2017 1 Wood
Note: I am using SQL Server 2016
SELECT LEAD ( [A], 1 ) OVER (ORDER BY [ID] asc) as Col1 FROM Table1 --- (Note I added an ID clmn)
SELECT Top 1 LEAD ( [B], 2 ) OVER (ORDER BY [ID] asc) as Col2 FROM Table1
SELECT ROW_NUMBER() OVER (ORDER BY [ID] asc) AS RowNumber, * FROM Table1 WHERE RowNumber BETWEEN x AND y
Then insert all that into a final table... Simple question = simple answer. I'm just relatively new to sql so it was difficult to figure out on my own.

Dynamic columns col1 Col2 Col3 Col4

I have a table in that there are 4 columns , columns might get added or deleted on regular interval. I need a dynamic query which handle the columns on run time basis and perform a calculation.
Below are my structure of my table along with sample of records.
ID, col1, col2, col3, col4
1 '2016-08-09' '2016-08-09' '2016-08-09' '2016-08-09'
2 '2016-08-10' '2016-08-10' '2016-08-13' '2016-08-04'
I want result in which my date difference should come in each columns and there should one total columns should append which give total count of those columns for particular ID. Result set should be like below.
ID col1 Col2 Col3 Col4 Total
1 6 6 6 6 24
2. 6 7 8 8 29
Tested, works well. :)
--create table structure
create table #test1 (ID int, col1 date, col2 date, col3 date, col4 date)
go
--insert sample data
insert #test1
select 1, '2016-08-09', '2016-08-09', '2016-08-09', '2016-08-09'
union all
select 2, '2016-08-10', '2016-08-10', '2016-08-13', '2016-08-04'
union all
select 3, '2016-08-10', '2016-08-10', NULL, '2016-08-04'
--below is solution
with cte_test1 (id, dif1, dif2, dif3, dif4) as
(
select id,
datediff(day, col1, getdate()) as dif1,
datediff(day, col2, getdate()) as dif2,
datediff(day, col3, getdate()) as dif3,
datediff(day, col4, getdate()) as dif4
from #test1
)
select id,dif1,dif2,dif3,dif4,ISNULL(dif1,0)+ISNULL(dif2,0)+ISNULL(dif3,0)+ISNULL(dif4,0) as difTotal
from cte_test1
RESULT:

Update to get check_order

I have a table with values,
col1 col2 col3
1 0 ABA
1 0 ABB
1 0 ABC
2 0 BBA
2 0 BBB
2 0 BBC
I am trying to update the table to see the number of repetition of col1, in this case col1 has repeated 3 times so each update to col2 incremented by 1.
Required output after the update table
col1 col2 col3
1 1 ABA
1 2 ABB
1 3 ABC
2 1 BBA
2 2 BBB
2 3 BBC
A simple row_number() -ing should work
;with TMP as (
select *, row_number() over (partition by col1 order by col3) as RowNum
from tbl
)
update TMP set col2=RowNum
Where
tbl: is your table name
partition by col1: resets the row numbering for each col1 group
order by col3: is the basis for numbering within a col1 group
Assuming you are intending col3 to be in non-descending order, this should do it:
UPDATE MyTable
SET col2=(SELECT COUNT(*)
FROM MyTable AS T2
WHERE T2.col1=T1.col1 AND T2.col3<=T1.col3)
FROM MyTable AS T1
You will get duplicates in col2, if there are duplicates in col3 for a particular col1 value.
In case you are interested, here is a pretty verbose (and more expensive execution wise) solution using a ranking function. It has the same issue (i.e., the count gets repeated) for duplicates in col1/col3, as the previous solution:
UPDATE MyTable
SET col2=(
-- In the following query, DISTINCT merges rank dups caused by col3 dups
-- SELECT TOP(1) MyRank would also work.
SELECT DISTINCT MyRank
FROM (
SELECT col3,
DENSE_RANK() OVER (PARTITION BY col1 ORDER BY col3) AS MyRank
FROM MyTable
WHERE col1=UpdatedTable.col1
) As RankTable
WHERE RankTable.col3=UpdatedTable.col3)
FROM MyTable AS UpdatedTable

Resources