Assign Numbers to Groups in Calculated Column SQL Server - sql-server

This is probably extremely easy however for some reason I am having difficulty in pinpointing exactly how to do this. I have a list of names and cities associated with those names. I want to assign a number in a calculated column based on 1) name and 2) city. Example code below:
Name | City | Calculated Column
John NYC 1
John NYC 1
John NYC 1
John LA 2
John LA 2
Chris NYC 1
Chris SF 2
Christ SF 2
Chris LA 3
I am assuming I need to use an over and partition function, but have not been able to properly calculate the 'Calculated Column' above. Any assistance would be greatly appreciated. Thanks so much in advance!

I think you can use dense_rank as below:
Select *, [Computed Column]= dense_rank() over(Partition by [Name] order by City)
from yourtable

CREATE TABLE TEST
(
NAME VARCHAR(10),
CITY VARCHAR(5)
)
INSERT INTO TEST
VALUES
('John','NYC'),
('John','NYC'),
('John','NYC'),
('John','LA'),
('John','LA'),
('Chris','NYC'),
('Chris','SF'),
('Christ','SF'),
('Chris','LA')
SELECT NAME,CITY,dense_rank() OVER(partition by name ORDER BY city desc) calculated column
FROM TEST
---output---
NAME CITY calculated column
Chris SF 1
Chris NYC 2
Chris LA 3
Christ SF 1
John NYC 1
John NYC 1
John NYC 1
John LA 2
John LA 2

Related

Dynamic Sql Filter using tables

Any ideas on how this should be done with T-SQL queries?
I have two tables, Table A contain records I want to return but filter through. Table B contains the list of filters and class categories. New records are added to Table A all the time. The goal is to dynamically categorized records in Table A based on the filters listed in Table B.
Example:
Table A
Name
------------
John Doe
Mary Lamb
Peter Pan
Tom Sawyer
Suzie Lamb
Nancy Lamb
Josh Reddin
Table B:
Filter | Category
----------------------
John%Doe% | Team 1
%Lamb% | Team 2
Tom% | Team 1
Desired output:
Name | Category
John Doe | Team 1
Tom Sawyer | Team 1
Mary Lamb | Team 2
Suzie Lamb | Team 2
Nancy Lamb | Team 2
Peter Pan |
Josh Reddin |
I thought about doing the following but not sure if that's the best solution:
SELECT Filter, category from TableB (Get list of filters)
Using SQL Loop through filters returned in (1.) and find matches in Table A using LIKE.
Example:
SELECT name, Category
FROM Table A, Table B
WHERE Table A.Name Like (CURRENT filter FROM B)
Insert/append record(s) returned in (2.) into TempTable
SELECT *
FROM TempTable (this returns Names and categories as shown in the desired output)
UNION
SELECT *
FROM Table A
RIGHT OUTER JOIN TempTable on NAME
WHERE Category in null
(This returns rows with no categories found...Peter Pan and Josh Reddin)
Any ideas?
How about performance?
Thanks.
You can use combination of like and left join
select a.Name,b.Category
from tableA a left join tableB b on a.name like b.Filter

SQL Server 2008 Perform a draw between 2 tables

I have 2 tables on SQL Server 2008, each one has a single column and the same rows count number:
USERS OPERATION
Name Operation
----------- -----------
John W383
William R823
Karen X933
Peter M954
Alex S744
I need to perform every week a random draw between the 2 tables to get something like the follow and save it into a 3rd. table:
DRAW_RESULT:
Name Operation_Assigned Week_Number
----------------------------------------------
Peter M954 2
William W383 2
John S744 2
Alex X933 2
Karen R823 2
Name Operation_Assigned Week_Number
----------------------------------------------
William R823 3
Alex M954 3
Karen X933 3
John S744 3
Peter W383 3
How can I do this using T-SQL?
If I understood correctly what you're doing, something like this should work:
select name, operation from (
select
row_number() over (order by (select null)) as RN,
name
from
users
) U join (
select
row_number() over (order by newid()) as RN,
operation
from
operation
) O on U.RN = O.RN
Edit: row_number with newid() works, so removed the extra derived table.
Here's also SQL Fiddle to test this.

Getting ROW_NUMBER to repeat if field meets a condition

I need ROW_NUMBER to assign data to a specific user if a condition is met.
ROW_NUMBER will increment normally until a duplicate value is found. When the duplicate value is found, I need it to use the same ROW_NUMBER until a new value is found.
For instance...
When using
SELECT ROW_NUMBER() OVER (ORDER BY COMPANY) AS rownum
,Company
,Contact
FROM TABLE
We can obviously expect this result
rownum Company Contact
1 BOB'S BURGERS BOB
2 STEVE'S SARDINES STEVE
3 STEVE'S SARDINES JERRY
4 STEVE'S SARDINES MARY
5 LARRY's LOBSTER LARRY
6 CHRIS' COWS CHRIS
What I'm trying to get is this. Whenever the Company name doesn't change, repeat the ROW_NUMBER and continue to increment the number when the company does change
rownum Company Contact
1 BOB'S BURGERS BOB
2 STEVE'S SARDINES STEVE
2 STEVE'S SARDINES JERRY
2 STEVE'S SARDINES MARY
3 LARRY'S LOBSTER LARRY
4 CHRIS' COWS CHRIS
I'm using this condition to see if the company matches the previous company name. It returns a 2 if the condition is true
ROW_NUMBER() OVER (PARTITION BY COMPANY ORDER BY COMPANY) AS SameCompany
You want DENSE_RANK not ROW_NUMBER. Try this:
SELECT DENSE_RANK() OVER (ORDER BY COMPANY) AS rownum
,Company
,Contact
FROM TABLE

sql server pivot string from one column to three columns

I've been approaching a problem perhaps in the wrong way. I've researched pivot examples
http://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query
How to create a pivot query in sql server without aggregate function
but they aren't the type I'm looking for.. or perhaps I'm approaching this in the wrong way, and I'm new to sql server.
I want to transform:
Student:
studid | firstname | lastname | school
-----------------------------------------
1 mike lee harvard
1 mike lee ucdavis
1 mike lee sfsu
2 peter pan chico
2 peter pan ulloa
3 peter smith ucb
Desired output: (note for school, want only 3 columns max.)
studid| firstname | lastname | school1 | school2 | school3
---------------------------------------------------------------------
1 mike lee Harvard ucdavis sfsu
2 peter pan chico ulloa
3 peter smith ucb
The tutorials I see shows the use of Sum() , count() ... but I have no idea how to pivot string values of one column and put them into three columns.
You can get the results you desire by taking max(school) for each pivot value. I'm guessing the pivot value you want is rank over school partitioned by student. This would be the query for that:
select * from
(select *, rank() over (partition by studid order by school) rank from student) r
pivot (max(school) for rank in ([1],[2],[3])) pv
note that max doesn't actually do anything. the query would return the same results if you replaced it with min. just the pivot syntax requires the use of an aggregate function here.

Crystal Report do not do the sum on Database "Cache"

I am using Crystal report to do a sum over 3 columns. The table structure looks like:
table #test (Country VARCHAR(10), Name VARCHAR(10), Weight VARCHAR(10), Qty INT)
I wrote a query in the crystal command pane when I do the connection:
SELECT Country, SUM(Qty) As Qty, Name, Weight FROM #test GROUP BY Country, Name, Weight
I should get something like:
CANADA 2 John 200
US 1 John 160
US 2 Mike 180
US 6 Sam 90
However, the crystal report does not sum the field, instead it pulls every single row, and the result looks like I write the query:
SELECT Country, Qty, Name, Weight FROM #test
CANADA 1 John 200
CANADA 1 John 200
US 1 John 160
US 2 Mike 180
US 3 Sam 90
US 3 Sam 90
By the way, the backend database is called "Cache". It might be due to there are some hidden characters, but I cannot see them. I have used replace (char(10)), replace (char(13) and trim to try to clean.
I also try to pull the table column directly without writing the query, but I do not know how to sum three columns (Country, Name and Weight). I only know how to sum one column. By the way, the request do not want the details, only the sum over these three columns;
First group by country.
Create one more group by quantity
Create one more group by name
Place weight in details and take the sum for all 3 groups if you need or only particular group
Supress tje details.

Resources