Here's the instruction:
Display the two largest capital and their corresponding company names in the DocStatus table.
Here's the table DocStatus:
DocID Company Capital
2001 Teewai.com Inc. 250000.00
2002 Fave Company 250000.00
2003 Goldilocks Bakeshop Corp 500000.00
2004 Collegian Exponent Inc. 100000.00
2005 Uniphil Computer Inc. 250000.00
Question:
What's the correct query for this? Thank you.
(500000 and 250000 are the top two but 3 companies have the same capital of 250000)
If you need only the topmost 2 records then try this:
SELECT TOP 2 *
FROM DocStatus
ORDER BY Capital DESC,Company
It will sort the result in descending order of Capital. And if multiple records have same Capital, it will sort them in the ascending order of Company Name. And finally, selects the top 2 records.
The result will be:
DOCID COMPANY CAPITAL
2003 Goldilocks Bakeshop Corp 500000
2002 Fave Company 250000
See result in SQL Fiddle
OR
If you want the companies which have the 1st and 2nd highest capital, use this:
SELECT TOP(2) WITH TIES * FROM DocStatus
ORDER BY Capital DESC
The beauty of this clause is that it can be used with the WITH TIES clause to retrieve all similar rows to a base result set.
The result will be:
DOCID COMPANY CAPITAL
2003 Goldilocks Bakeshop Corp 500000
2001 Teewai.com Inc. 250000
2002 Fave Company 250000
2005 Uniphil Computer Inc. 250000
Read more here.
try this !
select top(2) with ties * from table order by Capital desc
SEE DEMO
Related
I have the following data:
CompanyID
Department
No of People
Country
45390
HR
100
UK
45390
Service
250
UK
98712
Service
300
US
39284
Admin
142
Norway
85932
Admin
260
Germany
I wish to know how many people belong to the same department from different countries?
Required Output
Department
No of People
Country
HR
100
UK
Service
250
UK
300
US
Admin
142
Norway
260
Germany
I was able to get the data but the Department was repeated by this query.
""" select Department, Country,count(Department) from dataset
group by Country,Department
order by Department """
How can I get the desired output?
The result set that you are producing is not really a relational result set. Why? Because rows depend on what is in the "previous" row. And in a relational database, there is no such thing as a "previous" row. This type of processing is often handled in the application layer.
Of course, SQL can do what you want. You just need to be careful:
select (case when 1 = row_number() over (partition by Department order by Country)
then Department
end) as Department,
Country, count(*) as num_people,
from dataset
group by Country,Department
order by Department, Country;
Note that the order by needs to match the window function clause to be sure that what row_number() considered to be the first row is really the first row in the result set.
I am using SQL Server
I have a table
id--dish--restaurant
1 pasta Italian
2 noodles Chinese
3 beef Chinese
4 noodles Chinese
How can I use COUNT() to get the following result, to count each dish for every UNIQUE restaurant
Restaurant Dish Count
Italian 1
Chinese 3
Any suggestions would be helpful.
That's a simple aggregation query:
select restaurant, count(*) dish_count
from mytbale
group by restaurant
Use group by:
Select restaurant, count(*)
From table
Group by restaurant
Replacing table with your table's name
This is a heavily simplified version of an SQL problem I'm dealing with. Let's say I've got a table of all the cities in the world, like this:
country city
------------
Canada Montreal
Cuba Havanna
China Beijing
Canada Victoria
China Macau
I want to count how many cities each country has, so that I would end up with a table as such:
country city_count
------------------
Canada 50
Cuba 10
China 200
I know that I can get the distinct country values with SELECT distinct country FROM T1 and I suspect I need to construct a subquery for the city_count column. But my non-SQL brain is just telling me I need to loop through the results...
Thanks!
Assuming the only reason for a new row is a unique city
select country, count(country) AS City_Count
from table
group by country
This is my SQL View - lets call it MyView :
ECode SHCode TotalNrShare CountryCode Country
000001 +00010 100 UKI United Kingdom
000001 ABENSO 900 USA United States
000355 +00012 1000 ESP Spain
000355 000010 50 FRA France
000042 009999 10 GER Germany
000042 +00012 999 ESP Spain
000787 ABENSO 500 USA United States
000787 000150 500 ITA Italy
001010 009999 100 GER Germany
I would like to return the single row with the highest number in the column TotalNrShare for each ECode.
For example, I’d like to return these results from the above view:
ECode SHCode TotalNrShare CountryCode Country
000001 ABENSO 900 USA United States
000355 +00012 1000 ESP Spain
000042 +00012 999 ESP Spain
000787 ABENSO 500 USA United States
001010 009999 100 GER Germany
(note in the case of ECode 000787 where there are two SHCode's with 500 each, as they are the same amount we can just return the first row rather than both, it isnt important for me which row is returned since this will happen very rarely and my analysis doesnt need to be 100%)
Ive tried various things but do not seem to be able to return either unqiue results or the additional country code/country info that I need.
This is one of my attempts (based on other solutions on this site, but I am doing something wrong):
SELECT tsh.ECode, tsh.SHCode, tsh.TotalNrShare, tsh.CountryCode, tsh.Country
FROM dbo.MyView AS tsh INNER JOIN
(SELECT DISTINCT ECode, MAX(TotalNrShare) AS MaxTotalSH
FROM dbo.MyView
GROUP BY ECode) AS groupedtsh ON tsh.ECode = groupedtsh.ECode AND tsh.TotalNrShare = groupedtsh.MaxTotalSH
WITH
sequenced_data AS
(
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY ECode ORDER BY TotalNrShare) AS sequence_id
FROM
myView
)
SELECT
*
FROM
sequenced_data
WHERE
sequence_id = 1
This should, however, give the same results as your example query. It's simply a different approach to accomplish the same thing.
As you say that something is wrong, however, please could you elaborate on what is going wrong? Is TotalNrShare actually a string for example? And is that messing up your ordering (and so the MAX())?
EDIT:
Even if the above code was not compatible with your SQL Server, it shouldn't crash it out completely. You should just get an error message. Try executing Select * By Magic, for example, and it should just give an error. I strongly suggest getting your installation of Management Studio looked at and/or re-installed.
In terms of an alternative, you could do this...
SELECT
*
FROM
(SELECT ECode FROM MyView GROUP BY ECode) AS base
CROSS APPLY
(SELECT TOP 1 * FROM MyView WHERE ECode = base.ECode ORDER BY TotalNrShare DESC) AS data
Ideally you would replace the base sub-query with a table that already has a distinct list of all the ECodes that you are interested in.
try this;
with cte as(
SELECT tsh.ECode, tsh.SHCode, tsh.TotalNrShare, tsh.CountryCode, tsh.Country,
ROW_NUMBER() over (partition by ECode order by SHCode ) as row_num
FROM dbo.MyView)
select * from cte where row_num=1
Name ExactDate Presents Location
bob1 2011 1 home
bob2 2008 2 school
bob2 2012 3 school
mary2 1986 4 school
mary1 2001 5 home
mary1 2012 6 home
kate1 2011 7 home
kate1 2012 8 home
kate2 2011 9 school
celia2 2011 10 school
celia2 1986 11 school
celia1 1972 12 home
celia1 2012 14 home
celia2 2012 13 school
This problem is done in SQL in MS Access 2003 for a query.
So the goal is we subtract the amount of presents kate got from celia on the same year ( but since there are a few different present values for the same year we choose to have priority of home > school....for example celia and kate both receive presents in 2012 but celia gets both home presents and school presents in 2012 in which case we choose her home present value to do the calculation) and out put should be something like the following:
Name ExactDate PresentsDiff
celiaminuskate 2011 3
celiaminuskate 2012 6
So far I have :
SELECT 'celiaminuskate'AS [NAME],T1.[date] AS [EXACT DATE],
T1.presents T2.presents AS [PRESENTS DIFF]
FROM Some_Table T1, Some_Table T2
part that I think needs to be fixed??
WHERE (T1.Name = 'celia1'>'celia2')
AND (T2.Name = 'kate1'>'kate2')
AND T2.ExactDate = T1.ExactDate
to indicate priority? I'm not too sure how to do it
ORDER BY T1.ExactDate
I created this query and saved it as qryCeliaAndKateGiftDates. It just returns the distinct ExactDate values for which celia and kate both had gifts recorded.
Notice I re-named your Name field to Recipient, because Name is a reserved word.
SELECT DISTINCT celia.ExactDate
FROM
[SELECT ExactDate
FROM Some_Table
WHERE Recipient Like "celia*"
]. AS celia
INNER JOIN [
SELECT ExactDate
FROM Some_Table
WHERE Recipient Like "kate*"
]. AS kate
ON celia.ExactDate = kate.ExactDate
ORDER BY celia.ExactDate;
Then I used correlated subqueries to return the correct Presents values for celia and kate on each of those ExactDates.
SELECT
raw.recipients AS [NAME],
raw.ExactDate AS [EXACT DATE],
(raw.celia_presents - raw.kate_presents) AS [PRESENTS DIFF]
FROM
[SELECT
'celiaminuskate' AS recipients,
dates.ExactDate,
(SELECT TOP 1 Presents
FROM Some_Table
WHERE
Recipient Like "celia*"
And ExactDate = dates.ExactDate
ORDER BY Location) AS celia_presents,
(SELECT TOP 1 Presents
FROM Some_Table
WHERE
Recipient Like "kate*"
And ExactDate = dates.ExactDate
ORDER BY Location) AS kate_presents
FROM qryCeliaAndKateGiftDates AS dates]. AS raw;
It returns the results you requested when run from Access 2003. However correlated subqueries are notoriously slow, so I'll be interested to see what other answers you get.