How to select group of data and show one by one? - sql

I have a table called leads and it has one column company. Each company puts up several rows (or leads) in this table. So the problem is that I use a simple SELECT * FROM Leads and display the output but some of the companies are pissed off that preference is given to one company over another but I cannot tell them it’s because they entered the lead first. So instead I’m looking for a solution where exactly 1 lead of each company is output and then when it exhausts showing 1 lead of each company the next set of 1-lead only appears.
So for example consider this as input table
Lead ID Company
1 ABC
2 ABC
3 ABC
4 BCD
5 CDE
6 EFG
7 EFG
8 CDE
9 ABC
10 BCD
11 ABC
Then I need something like
Lead ID Company
1 ABC
4 BCD
5 CDE
6 EFG
2 ABC
10 BCD
7 EFG
3 ABC
8 CDE
9 ABC
11 ABC
So here exactly 1 lead of each company appears and then the next company’s lead appears. When a particular companies leads are exhausted the remaining only appear. This is why in the last 2 results ABC appears twice as no other companies have unlisted leads.

This is probably the closest you can get:
select *
from Tab
order by
row_number() over (partition by Company order by LeadID)
The result will be ordered kind of randomly, you might add LeadID to the ORDER BY, see fiddle

;With Data As (
Select
*,
Rank() Over (Partition By Company Order By LeadID) Rnk
From LeadTableName
)
Select * From Data
Order By Rnk, Company

Related

Select a record a variable number of times based on two different fields on the same table

I'm not an expert of ANSI SQL and I need to write the following query.
This is the table from which I start:
ID
Max_Recurrency
Priority
abc
2
1
abc
2
450
abc
2
12
def
1
827
def
1
44
def
1
112
ghi
2
544
ghi
2
4
ghi
2
95
ghi
2
25
The output I need is something like this:
ID
Max_Recurrency
Priority
abc
2
450
abc
2
12
def
1
827
ghi
2
544
ghi
2
95
In other words, I need to select the ID of the record as many times as is indicated in the Max_Recurrency field and select the records with the highest Priority, i.e. excluding those with the lowest Priority if the Max_Recurrency field has a value less than the number of times the ID is repeated in the table.
Can anyone help me?
We can use ROW_NUMBER here:
WITH cte AS (
SELECT t.*, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Priority DESC) rn
FROM yourTable t
)
SELECT ID, Max_Recurrency, Priority
FROM cte
WHERE rn <= Max_Recurrency;

SQL Server - logical question - Get rank from IDs

I'm trying to write a query to solve a logical problem using Redshift POSTGRES 8.
Input column is a bunch of IDs and Order IDs and desired output is basically a rank of the ID as you can see in the screenshot.
(I'm sorry I'm not allowed to embed images into my StackOverflow posts yet)
If you could help me answer this question using SQL, that would be great! Thanks
Data
order id
id
size
desired output
1
abcd
2
1
1
abcd
2
1
1
efgh
5
2
1
efgh
5
2
1
efgh
5
2
1
efgh
5
2
2
aa
2
1
2
aa
2
1
2
bb
2
2
2
bb
2
2
SELECT
*,
DENSE_RANK() OVER (PARTITION BY order_item_id ORDER BY id) AS desired_result
FROM
your_table
DENSE_RANK() creates sequences starting from 1 according to the ORDER BY.
Any rows with the same ID will get the same value, and where RANK() would skip values in the event of ties DENSE_RANK() does not.
The PARTITION BY allows new sequences to be created for each different order_item_id.

Update rows based on rownumber in SQL Server 2012

Ive been given some data in a spreadsheet which will soon be going into an automated import so i cannot do any manual entry on the spreadsheet. The data basically has the following columns. Trayid, trayname, itemdescription and rownumber. I didnt build these tables myself or i would of built it differently but i have to stick to the format which is already set.
The Data that is being imported will look at followed.
Trayid | Trayname | ItemDescription | RowNumber
1 Tray 1 Product 1 1
Product 2 2
Product 3 3
Product 4 4
2 Tray 2 Product 1 1
Product 2 2
Product 3 3
Product 4 4
Product 5 5
What i need to do is update the trayid and trayname for each of the other rows following row 1, so for example it will look like.
Trayid | Trayname | ItemDescription | RowNumber
1 Tray 1 Product 1 1
1 Tray 1 Product 2 2
1 Tray 1 Product 3 3
1 Tray 1 Product 4 4
2 Tray 2 Product 1 1
2 Tray 2 Product 2 2
2 Tray 2 Product 3 3
2 Tray 2 Product 4 4
2 Tray 2 Product 5 5
Im guessing i need to use a curser or something but im not sure, i think it can be done by going down the rownumbers and stopping when it see's rownumber 1 again and then carrying on with the next trayid and trayname.
Sorry if what i need doesnt make sense, it was awkward to explain.
SQL tables have no inherent ordering. So you cannot depend on that. But, there is something that you can do:
Define an identity column in the source table.
Create a view on the source table that excludes the identity.
Bulk insert into the view.
This will assign a sequential number to rows in the same order as the original data. Let's call this id. Then you can do your update by doing:
with toupdate (
select t.*,
max(TrayId) over (partition by grp) as new_TrayId,
max(TrayName) over (partition by grp) as new_TrayName
from (select t.*,
count(TrayId) over (order by id) as grp
from t
) t
)
update toupdate
set TrayId = new_TrayId,
TrayName = new_TrayName
where TrayId is null;
The idea is to define groups of rows corresponding to each tray. The simple idea is to count the number of non-NULL values before any given row -- everything in a group will then have the same grp value. Window functions then spread the actual value through all rows in the group (using max()), and these values are used for the update.

Sort table by group with highest sum and displaying individual entries

I have following scenario where i want to order the table and arrange by groups having highest to lowest sum
name score
----------------
abc 10
pqr 9
abc 7
pqr 3
abc 10
xyz 7
pqr 7
xyz 3
xyz 2
now if we observe,
total (abc) = 10 + 7 + 10 = 27
total (pqr) = 9 + 3 + 7 = 19
total (xyz) = 7 + 3 + 2 = 12
How to sort the above table in SQL by group with highest sum and it should display individual entries?
Expected output:
----------------
name score
----------------
abc 10
abc 10
abc 7
pqr 9
pqr 7
pqr 3
xyz 7
xyz 3
xyz 2
SQLite doesn't have analytical/windowed functions, so you need to work out the different pieces of data yourself.
SELECT
yourTable.*
FROM
yourTable
INNER JOIN
(
SELECT name, SUM(score) AS score FROM yourTable GROUP BY name
)
AS totalScores
ON totalScores.name = yourTable.name
ORDER BY
totalScores.score DESC,
yourTable.name,
yourTable.score DESC
In this query, there is a sub-query. The sub-query calculates the totalScore for each name.
This then lets you put that total score in the ORDER BY clause. Note, I don't select the total score in my results, you can but it's not necessary.
Also, I've put the name in the ORDER BY. In this way, if there is a tie with more than one name sharing the same total score, the name that is first alphabetically will be shown first.
If you use SQL-Server, one way is using SUM(score)OVER(PARTITION BY name)
SELECT name,
score,SUM(score)OVER(PARTITION BY name)
FROM dbo.TableName
ORDER BY SUM(score)OVER(PARTITION BY name) DESC,
score DESC
DEMO
OVER Clause (Transact-SQL)

Difficulty in creating update totals query on same table

Consider the following table:
ID nonUniqueID value total
--------------------------
1 12345 5 x
2 12345 10 x
3 789 20 x
4 789 5 x
I need to make a query something like this (psuedo SQL), which will work within Access 2007:
UPDATE table
SET total = SUM(value)
WHERE nonUniqueID IS SAME;
The result should be as follows:
ID nonUniqueID value total
--------------------------
1 12345 5 15
2 12345 10 15
3 789 20 25
4 789 5 25
I've tried group bys, but I got odd results that quite frankly, I could not interpret. Does anybody know how I could achieve something like this?
Not sure if this works in Access or not, but give it a try:
update table t1
inner join (
select nonUniqueID, sum(value) as SumValue
from table
group by nonUniqueID
) t2 on t1.nonUniqueID = t2.nonUniqueID
set t1.total = t2.SumValue
Update: Based on this question, it looks like it is not going to work. But give it a shot! If it doesn't, you can use the approach suggested in that question.
Another possible option:
update t
set total = (select SUM(value) from table where nonUniqueID = t.nonUniqueID)
from table t