I have the following tables in SQL Server:
COMMANDLINES
: ID_LINE - ID_COMMAND - ID_ARTICLE - QUANTITYCOMMAND
: ID_COMMAND - ID_CLIENT - PRICE - PRINTEDCLIENT
: ID_CLIENT - FULL_NAME - SSN - PH_NUM - MOBILE - USERNAME - PASSWORDARTICLE
: ID_ARTICLE - DES - NAME - PRICE - TYPE - CURRENT_QTT - MINIMUM_QTTID_COMMAND
fromCOMMANDLINES
referencesCOMMAND.ID_COMMAND
ID_CLIENT
fromCOMMAND
referencesCLIENT.ID_CLIENT
ID_ARTICLE
fromCOMMANDLINES
referencesARTICLE.ID_ARTICLE
I need to create a view
where I need to show all COMMANDLINES
that have the best client (the one with the highest total of PRICE
) and then I need to order them by ID_COMMAND
in a descending order AND by ID_LINE
in ascending order.
Sample data:
COMMANDLINE
table:
COMMAND
table:
Only these 2 are needed to resolve the problem. I added the other just for more information.
Sample output:
To be honest, I'm not sure if both outputs are supposed to be "output" at the same time or that I need 2 VIEWS
for each output.
WHAT HAVE I DONE SO FAR:
I looked through what I could find on StackOverflow about MAX
of SUM
, but unfortunately, it has not helped me much in this case. I always seem to be doing something wrong.
I also found out that in order to use ORDER BY
in VIEWS
you need to, in this case, use TOP
, but I've no idea how to apply it correctly when I need to select all of the COMMANDLINES
. In one of my previous things, I used the following SELECT TOP
:
create view PRODUCTS_BY_TYPE
as
select top (select count(*) from ARTICLE
where CURRENT_QTT > MINIMUM_QTT)*
from
ARTICLE
order by
TYPE
This allowed me to show all PRODUCT
data where the CURRENT_QTT
was more than the minimum ordering them by type, but I can't figure out for the life of me, how to apply this to my current situation.
I could start with something like this:
create view THE_BEST
as
select COMMANDLINE.*
from COMMANDLINE
But then I don't know how to apply the TOP
.
I figured that first, I need to see who the best client is, by SUM
-ing all of the PRICE
under his ID and then doing a MAX
on all of the SUM
of all clients.
So far, the best I could come up with is this:
create view THE_BEST
as
select top (select count(*)
from (select max(max_price)
from (select sum(PRICE) as max_price
from COMMAND) COMMAND) COMMAND) COMMANDLINE.*
from COMMANDLINE
inner join COMMAND on COMMANDLINE.ID_COMMAND = COMMAND.ID_COMMAND
order by COMMAND.ID_COMMAND desc, COMMANDLINE.ID_LINE asc
Unfortunately, in the select count(*)
the COMMAND
is underlined in red (a.k.a. the 3rd COMMAND
word) and it says that there is "no column specified for column 1 of COMMAND
".
EDIT:
I've come up with something closer to what I want:
create view THE_BEST
as
select top (select count(*)
from (select max(total_price) as MaxPrice
from (select sum(PRICE) as total_price
from COMMAND) COMMAND) COMMAND)*
from COMMANDLINE
order by ID_LINE asc
Still missing the ordered by ID_COMMAND
and I only get 1 result in the output when it should be 2.