Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# SQL Server VIEW Query

I need to create a VIEW query...

For example:

Name                   Count
------------------------------
Kaganoff Benzion       122  
Van Gennep             443  
Michelen Luis          656  
kraig Beno             333  
Mogrobejo Endika       555  

*all the names in the "Name" column containing two words with a space in between.

Now, I need to order by the FIRST letter of the first word and the FIRST letter of the second word ascending and by Count descending...

The outcome should be:

Name                   Count
------------------------------
kraig Beno             333  
Kaganoff Benzion       122  
Mogrobejo Endika       555  
Michelen Luis          656  
Van Gennep             443  

Lets see if you can :)

like image 894
Joy Avatar asked Sep 22 '26 06:09

Joy


2 Answers

something like this query should work (I've set up my own temp table with your data)

create table #Temp (Name varchar(100), [Count] int)
insert into #Temp (Name, [Count]) VALUES ('Kaganoff Benzion', 122)
insert into #Temp (Name, [Count]) VALUES ('Van Gennep', 443)
insert into #Temp (Name, [Count]) VALUES ('Michelen Luis', 656)
insert into #Temp (Name, [Count]) VALUES ('kraig Beno', 333)
insert into #Temp (Name, [Count]) VALUES ('Mogrobejo Endika', 555)

select
SUBSTRING(Name, 1, PATINDEX('% %', Name)) AS FirstName,
SUBSTRING(Name, PATINDEX('% %', Name) + 1, LEN(Name) - PATINDEX('% %', Name)) AS SecondName,
[Count]
from #Temp
ORDER BY SUBSTRING(Name, 1, 1), SUBSTRING(Name, PATINDEX('% %', Name) + 1, 1), [Count] DESC

drop table #Temp
like image 142
openshac Avatar answered Sep 23 '26 20:09

openshac


I'd go about this with a common table expression.

DECLARE @data TABLE (Name varchar(50), NameCount int);

INSERT INTO @data (Name, NameCount)
SELECT 'Kaganoff Benzion', 122
UNION SELECT 'Van Gennep', 443
UNION SELECT 'Michelen Luis', 656
UNION SELECT 'kraig Beno', 333
UNION SELECT 'Mogrobejo Endika', 555;

--Now that we have the data setup, use a CTE...

WITH NamesAndLetters AS
(
    SELECT 
          SUBSTRING(UPPER(Name), 1, 1) [FirstNameLetter]
        , SUBSTRING(UPPER(Name), PATINDEX('% %', Name) + 1, 1) [LastNameLetter]
        , Name
        , NameCount
    FROM @data
)
SELECT Name, NameCount
FROM NamesAndLetters 
ORDER BY 
      FirstNameLetter ASC
    , LastNameLetter ASC
    , NameCount DESC

Sorry for the first post...I didn't see that Name was one column at first.

like image 22
Aaron Daniels Avatar answered Sep 23 '26 19:09

Aaron Daniels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!