Is there a way to Merge SQL Server Row Query? - sql-server

Please look at my current summary query result :
id name mch
127664 ML 2
127666 ML 2
127667 ML 2
127670 ML 2
127671 ML 2
127672 ML 2
127674 ML 2
127675 ML 2
127678 ML 1
127680 ML 1
127665 ML 2
I want to merge row which has same value..
Just merge the name column.
And then here is my expected query :
id name mch
127664 ML 2
127666 2
127667 2
127670 2
127671 2
127672 2
127674 2
127675 2
127678 1
127680 1
127665 2
I already look for some problem but still not found.
I hope you want to guide me to handle this..

Well you could try a ROW_NUMBER trick here:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY name ORDER BY id) rn
FROM yourTable
)
SELECT
id,
CASE WHEN rn = 1 THEN name ELSE '' END AS name,
mch
FROM cte
ORDER BY
name,
id;
But typically this type of requirement would be better handled in your presentation layer (e.g. PHP or Java).

Your query should be like this :
WITH t AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY name ORDER BY id) counter
FROM table //nameofyourtable
)
SELECT
id,CASE WHEN counter = 1 THEN name ELSE '' END AS name, mch
FROM t ORDER BY
name,
id;

Related

How to calculate LCM value using SQL Server?

I have below data and I need to calculate LCM (Lowest calculate multiply) value based on group id using a T-SQL query. Your help would be appreciated.
Groupid GroupValue
------------------
1 2
1 4
1 6
2 5
2 5
2 10
3 3
3 12
3 6
3 9
Expected result is below.
Groupid GroupLCM
------------------
1 12
2 10
3 36
One possible way is to use tally tables like below
See working demo
; with detailedSet as
(
select
Groupid,
GroupValue=abs(GroupValue),
biggest=max(GroupValue) over (partition by Groupid),
totalNumbers= count(1) over (partition by Groupid)
from num
)
,
possibleLCMValues as
(
select Groupid, counter
from detailedSet b
cross apply
(
select counter= row_number() over ( order by (select null)) * biggest
from sys.objects o1 cross join sys.objects o2
)c
where c.counter%GroupValue =0
group by Groupid, counter
having count(1)=max(totalNumbers)
)
,
LCMValues as
(
select
Groupid,
LCM=min(counter)
from possibleLCMValues
group by Groupid
)
select * from LCMValues
I found the solution which I post on below stack flow question. In Final result table we just use max value again group id and we get LCM value.
Just note Like, I post this question for more optimize solution to remove for loop otherwise it working properly using for loop as well.
How to update the column without loop in SQL Server?

SQL Server | Finding out count and category

Table A
Owner row_no category
-------------------------
A 1 U
B 1 T
B 2 T
C 1 U
C 2 T
C 3 U
C 4 U
I'm looking for a solution that stores values into other table which should retrieve
row_no as 1 if the value is 1 and should return max(row_no)-1 if the value isn't 1.
category should be either T or U or both based on whether an owner has opted for only T or U or both in TABLE A.
Expected table output should be something like below.
Owner row_no category
---------------------------
A 1 U
B 1 T
C 3 Both
I tried using the below approach which turns out to be an error.
SELECT *
INTO B
FROM A
WHERE ROW_NO LIKE CASE
WHEN ROW_NO = 1 THEN ROW_NO
ELSE MAX(ROW_NO) - 1
END
Haven't figured out yet on retrieving the category!
Could you please help with correct approach?
Your logic is not completely clear to me. In particular, I assume here that your logic for reporting the row_no is to return 1 when the max value for an owner is 1, otherwise to return that max value minus 1.
We can try doing a simple aggregation query here to generate what you want.
SELECT
Owner,
CASE WHEN MAX(row_no) = 1 THEN 1 ELSE MAX(row_no) - 1 END AS row_no,
CASE WHEN COUNT(DISTINCT category) > 1 THEN 'Both' ELSE MAX(category) END AS category
FROM tableA
GROUP BY
Owner;
Demo
One method would be to use a GROUP BY:
WITH VTE AS(
SELECT *
FROM(VALUES ('A',1,'U'),
('B',1,'T'),
('B',2,'T'),
('C',1,'U'),
('C',2,'T'),
('C',3,'U'),
('C',4,'U')) V([Owner], Row_no, Category))
SELECT [Owner],
ISNULL(NULLIF(MAX(Row_no) - 1,0),1) AS Row_no,
CASE WHEN MIN(Category) = MAX(Category) THEN MAX(Category) ELSE 'Both' END AS Category --Assumes Category cannot have a value of NULL
FROM VTE
GROUP BY [Owner];

Find dup records with different extensions in SQL Server

I have a subscriptions table. Sample records:
SUBS_ID | SUBS Name
1 | SC FORM 124
2 | SC FORM 124-R
I need to find both the records, as the subscription name is exactly the same but just with an extension-R.
Really bad throwaway code written straight here and untested, but...
with cte As (Select Name, Id
From Subs
Where Name Not Like '%-R'
)
Select cte.Id, cte.Name, M.Name
From Subs As M
Join cte
On cte.Name + '-R' = M.Name
You can use row_Number and partition by as below:
Select * from (
Select *, DupeRecords = Row_number() over(partition by replace([Subs Name],'-R','') order by Subs_Id)
from #yoursubs
) a Where a.DupeRecords > 1
Based on your latest criteria:
So, in the above example when I query the table I should get all 3
records ...the first one being the base record and the remaining 2
being the extensions – SQL User 17 mins ago
SELECT distinct
0 as Subs_ID
, CASE WHEN SUBS_Name like '%-%' THEN left(SUBS_Name,charindex('-',SUBS_Name)-1) ELSE SUBS_Name END AS SUB_NAME_MAIN
, '' as Extension
FROM
subs
UNION
SELECT
Subs_ID
, CASE WHEN SUBS_Name like '%-%' THEN left(SUBS_Name,charindex('-',SUBS_Name)-1) ELSE SUBS_Name END AS SUB_NAME_MAIN
, CASE WHEN SUBS_Name like '%-%' THEN RIGHT(SUBS_Name, LEN(SUBS_Name) - charindex('-',SUBS_Name)+1) ELSE '' END AS Extension
FROM
subs
will produce the following result. A 'Master' row that is given an arbitray ID number of '0' and each row of that master's family and its extension.
Subs_ID SUB_NAME_MAIN Extension
----------- -------------------- --------------------
0 SC FORM 124
1 SC FORM 124
2 SC FORM 124 -R

Max Value with unique values in more than one column

I feel like I'm missing something really obvious here.
Using T-SQL/SQL-Server:
I have unique values in more than one column but want to select the max version based on one particular column.
Dataset:
Example
ID | Name| Version | Code
------------------------
1 | Car | 3 | NULL
1 | Car | 2 | 1000
1 | Car | 1 | 2000
Target status: I want my query to only select the row with the highest version value. Running a MAX on the version column pulls all three because of the distinct values in the 'Code' column:
SELECT ID
,Name
,MAX(Version)
,Code
FROM Table
GROUP BY ID, Name, Code
The net result is that I get all three entries as per the data set due to the unique values in the Code column, but I only want the top row (Version 3).
Any help would be appreciated.
You need to identify the row with the highest version as 1 query and use another outer query to pull out all the fields for that row. Like so:
SELECT t.ID, t.Name, GRP.Version, t.Code
FROM (
SELECT ID
,Name
,MAX(Version) as Version
FROM Table
GROUP BY ID, Name
) GRP
INNER JOIN Table t on GRP.ID = t.ID and GRP.Name = t.Name and GRP.Version = t.Version
You can also use row_number() to do this kind of logic, for example like this:
select ID, Name, Version, Code
from (
select *, row_number() over (order by Version desc) as RN
from Table1
) X where RN = 1
Example in SQL Fiddle
add the top statment to force the return of a single row. Also add the order by notation
SELECT top 1 ID
,Name
,MAX(Version)
,Code
FROM Table
GROUP BY ID, Name, Code
order by max(version) desc

SQL Update sequence data based upon date field

I am attempting to update a table that contains deed information. Specifically property ID, sale sequence, and deed date. The program generates the sale sequence data sequentially regardless of the deed date or prior deed information for the property in question.
[property_ID] [sale_number] [sale_deed_date]
1 1 01/15/1990
1 2 06/25/1970
1 3 08/12/1930
What I would like to accomplish is re-sequence sale_number data so they are in chronological order. Similar to this:
[property_ID] [sale_number] [sale_deed_date]
1 1 08/12/1930
1 2 06/25/1970
1 3 01/15/1990
Any help with this would be greatly appreciated.
You can do this by grabbing the correct order in a cte:
;WITH cte AS (SELECT property_ID, sales_number, sales_deed_date, rn = ROW_NUMBER() OVER (PARTITION BY Property_ID ORDER BY sales_deed_date) FROM tablename)
UPDATE t
SET t.sales_number = cte.rn
FROM tablename t
INNER JOIN cte ON t.property_ID = cte.property_ID AND t.sales_deed_date = cte.sales_deed_date

Resources