Outputting a column as a different number from a different table - sql-server

The goal is to rank the Movies table according to quantity in the Inventory table such that for each duplicate value, it skips the subsequent value so that the next non-duplicate value remains in its rightful position. Display MovieID, Latest Title, Price, and the Rank.
WhileMovieId ‘1’ from Movies table corresponds to MovieId ‘101’ of your Movie inventory table and so on.
These are the tables
Movies
MovieId
latest title
Price
1
Breaking Dawn
200.00
2
The Proposal
185.00
3
Iron Man 2
180.00
4
Up
180.00
5
The Karate Kid
190.00
6
How to train your Dragon
190.00
7
Spiderman 3
195.00
Movie Inventory
MovieId
Quantity
101
3
105
4
107
5
108
7
110
8
111
4
And this is my attempt at the code that is showing a lot of NULL
SELECT CASE
WHEN Movies.MovieId + 100 = MovieInventory.MovieID
THEN CAST(MovieInventory.MovieID AS INT)
END AS 'MovieId',
Movies.LatestTitle, Movies.Price,
DENSE_RANK() OVER (ORDER BY Movies.MovieId DESC) AS [Rank]
FROM Movies, MovieInventory WHERE MovieInventory.MovieID IS NOT NULL
GO

This is what you need.
Notes:
You need RANK not DENSE_RANK to achieve the result you want
You need to order by Quantity
Use proper JOIN syntax, not comma , joins
Use table aliases for better readability
The foreign and primary key relationships are weird: mi.MovieID appears to be varchar but when converted to int is 100 more than m.MovieID???
The calculation in the SELECT is not accessible to the JOIN conditions
Don't use apostrophes '' to quote column names
SELECT
mi.MovieId,
m.LatestTitle,
m.Price,
RANK() OVER (ORDER BY mi.Quantity DESC) AS [Rank]
FROM Movies m
JOIN MovieInventory mi ON TRY_CAST(mi.MovieID AS int) = m.MovieID + 100;

Related

How to collect all deference in rows between two periods?

I'm trying to see the difference between the two periods for a column.
For example, we see that sales decreased at the end of the month, and we need to see which products were not sold at the end of the month?
I can create SELECT to see quantity for each product for each period:
SELECT product_id, count(product_id) AS Count
FROM testDB
WHERE
sales_date IS NOT NULL
AND
delivery_date BETWEEN '2021-02-01 00:00:03.0000000' AND '2021-02-14 23:56:00.0000000'
GROUP BY
product_id
and the same SELECT with another period:
delivery_date BETWEEN '2021-02-14 00:00:03.0000000' AND '2021-02-28 23:56:00.0000000'
So, after these queries I see list for first period with 10 products with quantity and in second period I see list with 7 products with quantity. I can't get the difference between the lists of the two SELECTs. I tried to use != and NOT IN but without any results.
I will be very grateful for your help. Thanks
Sorry for the confusion. I meant the difference between the two selects:
The result of the first one (for first period):
Product_ID Count
grapes. 100
lime. 13
lemon. 15
cherry. 222
blueberry. 123
banana. 1
apple. 123
watermelon 56
and second one (for second period):
Product_ID Count
grapes. 10
lime. 1
lemon. 10
cherry. 2
blueberry. 13
banana. 12
and I wand to see difference between these selects:
Product_ID Count
apple. 0
watermelon. 0
So we did not sell any apples and watermelons in second period.
SELECT product_id, count(product_id) AS Count,delivery_date-sales_date as DIFFERENCE
FROM testDB
WHERE
sales_date IS NOT NULL
AND
delivery_date BETWEEN '2021-02-01 00:00:03.0000000' AND '2021-02-14 23:56:00.0000000'
GROUP BY
product_id
This should work for getting the difference between the 2 period columns.

How to select the value from the table based on category_id USING SQL SERVER

How to select the value from the table based on category_id?
I have a table like this. Please help me.
Table A
ID Name category_id
-------------------
1 A 1
2 A 1
3 B 1
4 C 2
5 C 2
6 D 2
7 E 3
8 E 3
9 F 3
How to get the below mentioned output from table A?
ID Name category_id
--------------------
1 A 1
2 A 1
4 C 2
5 C 2
7 E 3
8 E 3
Give a row number for each row based on group by category_id and sort by ascending order of ID. Then select the rows having row number 1 and 2.
Query
;with cte as (
select [rn] = row_number() over(
partition by [category_id]
order by [ID]
), *
from [your_table_name]
)
select [ID], [Name], [category_id]
from cte
where [rn] < 3;
Kindly run this query It really help You Out.
SELECT tbl.id,tbl.name, tbl.category_id FROM TableA as tbl WHERE
tbl.name IN(SELECT tbl2.name FROM TableA tbl2 GROUP BY tbl2.name HAVING Count(tbl2.name)> 1)
Code select all category_id from TableA which has Name entries more then one. If there is single entry of any name group by category_id then such data will be excluded. In above example questioner want to eliminate those records that have single Name entity like wise category_id 1 has name entries A and B among which A has two entries and B has single entry so he want to eliminate B from result set.

i have 4 table in sql and i want the data or all the table where one unique key is matched in four of them

I have a table ratings, bookmark, checkin, food in food table there is a unique key sno and this sno key is used in remaining three tables.
food table
sno name totalrating totalcheckin
1 nitesh 52 45
2 abhishek 4 9
3 divye 42 30
ratings table
sno datakey rated name
1 3 3.0 divye
1 6 4.0 shashank
bookmark table
sno datakey name
1 3 divye
1 6 shashank
Checkin table
sno datakey name
1 2 abhishek
1 6 shashank
I need data where datakey is 3 if not present show null values and data key column not repeated
like
0 1 2 3 4 5 6 7 8 9 10
sno name totalrating totalcheckin sno rated name sno name sno name
3 divye 42 30 1 3.0 divye 1 divye null null
your query should look like this:
SELECT f.sno, f.name, f.totalrating, f.totalcheckin,
r.sno, r.rated, r.name,
b.sno, b.name,
c.sno, c.name
FROM food AS f
LEFT JOIN ratings AS r
ON f.sno = r.datakey
LEFT JOIN bookmark AS b
ON f.sno = b.datakey
LEFT JOIN checkin AS c
ON f.sno = c.datakey
WHERE f.sno = 3
Here is SQL Fiddle to see how it's work.
Also I agree with the guys in the comment which are told you to read something about JOIN syntax. It's pretty and you can start here, or more specific for your problem is LEFT JOIN, that is the begin and good place to start. Also you can see that I use aliases in my query about that read here.
GL!
P.S. (edit) and if you have any question fill free to ask... Also I notice that you have name column in every table, if I understand relation between your table it's not necessary. You should store name only in first table (food) and with simple JOIN from there you can pull that data whenever you need it!

Use Sum in certain conditions

I have say the following rows
Country Population
IE 30
IE 20
UK 15
DE 20
DE 10
UK 20
BE 5
So basically I want to net the values together only for IE and DE... the rest I just want the values
So this would sum them all ..
Select Country, Sum(Population) From CountryPopulation group by Country
and I can add a where clause to exclude all other countries except IE and DE... but I also want these in the result set but just not summed.
So the table above would look like this when summed
Country Population
IE 50 -- Summed
UK 15 -- Orginal Value
DE 30 -- Summed
UK 20 -- Orginal Value
BE 5 -- Orginal Value
Problem is I can’t get a sum if, or case to work as the query has to be aggregated by group by. Only other way I can thing on is to
Sum all the IE and DE and union it with the rest of the data..
Or
Maybe use a CTE
Is there a nice slick way of doing this....
Select Country, Sum(Population)
From CountryPopulation
group by case when Country in ('IE','DE')
then 'IE_DE'
else Country
end
declare #t table (Country char(2), Population int)
insert into #t (Country, Population) values
('IE',30),
('IE',20),
('UK',15),
('DE',20),
('DE',10),
('UK',20),
('BE',5 )
; With Ordered as (
select Country,Population,CASE
WHEN Country in ('IE','DE') THEN 1
ELSE ROW_NUMBER() OVER (ORDER BY Country)
END as rn
from #t
)
select Country,rn,SUM(Population)
from Ordered
group by Country,rn
Produces:
Country rn
------- -------------------- -----------
BE 1 5
DE 1 30
IE 1 50
UK 6 15
UK 7 20
The trick is to just introduce a unique value for each row, except for the IE and DE rows that all get a 1. If the source rows all, actually, already have such a unique value then the CTE can be simplified (or avoided, at the expense of having to place the CASE expression in the GROUP BY as well as the SELECT)
You could also use UNION ALL and divide this query into two:
SELECT P.country,
P.population
FROM (SELECT country,
Population = Sum(population)
FROM dbo.countrypopulation cp
WHERE country IN ( 'IE', 'DE' )
GROUP BY country
UNION ALL
SELECT country, population
FROM dbo.countrypopulation cp
WHERE country NOT IN ( 'IE', 'DE' )
) P
ORDER BY P.population DESC
Even if this is not so concise it is readable and efficient.
sql-fiddle

How to use generate Id for different values in calculated columns?

I have a big query (which is already ordered as per my needs), one of the columns is calculated (varchar combination of other columns in the query). I need an incremental integer to identify this calculated column (duplicates should have the same id).
I can´t use rank because the order in which I need the incremental number uses another criteria than the one used to generate the calculated column.
This is what I need:
OrderByColumn CalculatedColumn GeneratedId
1 ggg 1
1 aaa 2
1 ggg 1
1 fff 3
2 vvv 4
2 ddd 5
3 ggg 1
4 rrr 6
5 aaa 2
5 ooo 7
5 kkk 8
8 vvv 4
9 aaa 2
Use
ROW_NUMBER() OVER (PARTITION BY XXX ORDER BY YYY)
assuming you are using SQL2005 or better
http://msdn.microsoft.com/en-us/library/ms186734.aspx
-- though like you said this doesn't solve your dupes with same ID thing - ahhh! Give me a moment - should be able to do this pretty easy
Edit:
Here you go -
http://sqlfiddle.com/#!3/2f014/2
-- Select stuff:
select vals.val as genid, ord.* from ord
-- Join back to a distinct list of CalculatedColumn with a row_number() to id them
inner join
(select calculatedcolumn, row_number() over (order by calculatedcolumn) as val from ord group by calculatedcolumn) as vals on vals.calculatedcolumn = ord.calculatedcolumn
order by ord.orderbycolumn
Of course this is using the calculated column in the subquery - so you will need to re-calculate unless you store the value in a temp table or table variable

Resources