Get the Rows separately based on the ID in sql - c#

I have a table as follows,
TypeID Name Date
-------------------------------
1 Carrot 1-1-2013
1 Beetroot 1-1-2013
1 Beans 1-1-2013
2 cabbage 1-1-2013
2 potato 1-1-2013
2 tomato 1-1-2013
2 onion 1-1-2013
If need 2 rows then it should return 2 rows from TypeId 1 and 2 rows from TypeId 2.If need the only 4 rows, means I have to get 4 rows from TypeId 1 and 4 rows from TypeId 2
but TypeId 1 has only 3 rows so we need to get only 3 rows for typeId 1
How to do that? Shall I add RowNumber?

For SQL Server;
EDIT: Your question changed slightly;
If you want want a maximum of x items per category, you can use ROW_NUMBER();
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY TypeID ORDER BY Name) rn FROM Table1
)
SELECT TypeID, Name, [Date] FROM cte
WHERE rn <=3 -- here is where your x goes
ORDER BY TypeID;
An SQLfiddle to test with.

You can write your query to order by the TypeID.
Then, if you're using SQL, you could use SELECT TOP N or LIMIT N (depending on the DB), or with TSQL and SQL Server, use TOP(N) to take the top N rows.
If you're using a LINQ based ORM from your C# code, then you can use Take(N), which automatically creates the appropriate query based on the provider details to limit the number of results.

I think you should use a query to select your 3 rows from type 1.....and then the however many rows from type 2 and then add the results together.

;With CTE(TypeID,Name,Date,RowNo)
AS
(
select *, ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) from TableVEG
)
Select Top(#noofRows*2) * from CTE where RowNo<=#noofRows order by rowno
The above query worked.. Thank u all... :-)

Related

Asp.net(C#), how to do sql statement that order by a counted field

I’m working on a project which is an online shop,
I want to show in a page the most sold items,
So my sql is
Select (*), Count(Product_ID) as n from Order_Details order by n desc.
But it doesn’t work. Can someone help?
You need to aggregate the data first, this can be done using the GROUP BY clause:
SELECT (*), COUNT(DISTINCT Product_ID)
FROM table
GROUP BY Product_ID
ORDER BY COUNT(DISTINCT Product_ID) DESC
The DESC keyword allows you to show the highest count first, ORDER BY by default orders in ascending order which would show the lowest count first.
SELECT (*), Max(DISTINCT Product_ID)
FROM table
GROUP BY Product_ID
ORDER BY Max(DISTINCT Product_ID) DESC
the most sold item you use max

How to display label based on maximum count in database? ASP.NET C#

I currently have a table called Order_Details. Here, all records are stored like the example shown below:
OrderID Product_Name
1 Alpha
2 Alpha
3 Alpha
4 Bravo
5 Charlie
I have used the following sql statement to determine which record occurs the most:
select top 1 Product_Name, count(*) from [Order_Details]
group by Product_Name
order by count(*) desc
Output is below:
Product_Name (No column name)
Alpha 10
Right now, I would like to enable a Label called "Best Sellers" to appear after executing the query above. The label is to only appear for Product_Name that has the highest count.
My question now is how to use the following SQL statement to check the values from the database and enable the label to appear.
select top 1 Product_Name, count(*) as cnt, 'Best Seller' as label1 from [Order_Details]
group by Product_Name
order by count(*) desc
See the fiddle here.
select top 1 Product_Name as 'Best Sellers', count(*) as 'Sales' from [Order_Details]
group by Product_Name
order by count(*) desc

T-SQL Find when a amount has reached a set value

I have a table with data like:
ID Amount Status
1 15.00 Paid
2 3.00 Paid
3 10.00 Awaiting
4 12.00 Awaiting
The system looks at this table to see if a customer has paid enough for a subscription. This uses a table to record payments. Once a day I need to see if the customer has met this requirement.
The solution looks nothing like the above table as it much more complex, but the issue remain the same and can be broken down to this.
I need to find a way to add the amounts up, but when the amount goes over 20, change the data in the table as follows:
ID Amount Status
1 15.00 Paid
2 3.00 Paid
3 2.00 Paid <= Customer has reached payment level
4 12.00 Cancelled <= Subsequent payment is cancelled
5 8.00 BForward <= Extra money is brought forward
Currently I am using a cursor, but performance is bad, as expected.
Does anyone know of a better way?
Generates the desired results. Not sure why you would want to update the original data (assuming this is transnational data)
Declare #Table table (ID int,Amount money,Status varchar(50))
Insert into #Table values
(1,15.00,'Paid'),
(2,3.00,'Paid'),
(3,10.00,'Awaiting'),
(4,12.00,'Awaiting')
;with cteBase as (
Select *
,SumTotal=sum(Amount) over (Order By ID)
From #Table
), cteExtended as (
Select *
,Forward = IIF(SumTotal>20 and SumTotal-Amount<20,SumTotal-20,0)
,Cancelled = IIF(SumTotal>20 and SumTotal-Amount>20,Amount,0)
From cteBase
)
Select ID,Amount,Status='Paid' from cteExtended Where Forward+Cancelled=0
Union All
Select ID,Amount=Amount-Forward,Status='Paid' from cteExtended Where Forward>0
Union All
Select ID,Amount,Status='Cancelled' from cteExtended Where Cancelled>0
Union All
Select ID=(Select Count(*) from cteBase)+Row_Number() over (Order by ID),Amount=Forward,Status='BForward' from cteExtended Where Forward>0
Order By ID
Returns
ID Amount Status
1 15.00 Paid
2 3.00 Paid
3 2.00 Paid
4 12.00 Cancelled
5 8.00 BForward

Algorithm in SQL / C# to get an exact number of rows depending on variable?

I need to get an automatic method to link certain number consumptions with a payment.
I have for example in my first table.
Payments
ID Amount
1 $5,000
Then I have the following Table:
Consumptions
ID Amount CreatedDate
1 1000 2015-07-01 13:59
2 1000 2015-07-01 19:15
3 1000 2015-07-02 01:01
4 1500 2015-07-02 08:44
5 1000 2015-07-03 05:00
6 800 2015-07-03 19:57
7 200 2015-07-03 21:32
8 500 2015-07-03 23:48
I want to have a way that considering the $5000 payment amount, it automatically chooses the best combination of consumptions that make up the $5,000 sum.
If SQL is difficult, it can also be done on C#.
You will need a CTE that recursively joins with itself and checks all possible combinations.
with Anchor
(
Select Id, Amount, 0 as Level
From Consumptions
),
with RecursiveJoin
(
Select Id, Amount, Level From Anchor
Where Level = 0
UNION ALL
-- generate all possible permutations of amounts
Select c2.Id, c1.Amount + c2.Amount, Level + 1
From RecursiveJoin c1
Left Join RecursiveJoin c2 on c1.Id < c2.Id -- eliminate self joins and palindromes
)
Select *
From RecursiveJoin c
Join Payments p on c.Amount = p.Amount
I'm not completely confident that my recursion is correct. Hopefully that gets you started on the concept.
I'll leave it to you to add fields that concatenate lists of Id's of consumptions in each recursion.
It will give you multiple matches since multiple combinations of consumptions could match a payment. You could find the one with fewest combinations by keeping count in the recursion.

names repeated in dropdown.(sql query )

SELECT ID,Name FROM Master
id Name
1 John
2 John
3 Jack
4 Max
5 Jack
6 Max
7 Max
using above query i get all names repeated in dropdown.
i have to bind data in dropdown foreach Name there have
respective ID How can i do that.
I don't know the logic behind the data, but to get one name only once you have to filter out duplicate names and settle for one of the ids from the duplicate names.
SELECT MIN(id), Name
FROM Master
GROUP BY Name
The query above will output the occurence with the lowest id for each name, given that the id column is numeric.
The reason that your distinct query does not work, is that distinct filters on all columns in the result set, so in this case both name and id are used for uniqueness.
If you for some reason need all the ids for each name you have to filter on the ASP.NET side or look up the ids in the database once you know which person was selected.
Try this query it will return grouped as one
SELECT GROUP_CONCAT(ID), Name FROM your_tbl Group BY Name
Only place the Name column you will get the unique output. I think the problem is that the distinct keyword checks the primary key which is different per each row so it returns all the columns you only have to place the Name column. ( my understanding about distinct )
SELECT distinct Name FROM Master
output
Jack
John
Max
-- Below is what i tested
-- Created a table
Create table mytable(
ID bigint identity primary key,
UserName varchar(50)
)
-- Insert the records
INSERT INTO dbo.mytable(UserName) VALUES('John')
INSERT INTO dbo.mytable(UserName) VALUES('John')
INSERT INTO dbo.mytable(UserName) VALUES('Jack')
INSERT INTO dbo.mytable(UserName) VALUES('Max')
INSERT INTO dbo.mytable(UserName) VALUES('Jack')
INSERT INTO dbo.mytable(UserName) VALUES('John')
-- If i use below query
select distinct * from mytable
ID UserName
1 John
2 John
3 Jack
4 Max
5 Jack
6 John
-- and if i use this
select distinct UserName from mytable
output
Jack
John
Max
-- I think you should not allow the user to enter multiple users with the same name
-- what do you think about this
select UserName +' '+CAST(ID as varchar) as [Users] from mytable
John 1
John 2
Jack 3
Max 4
Jack 5
John 6
-- IN your code you can create a list<string,int> and stored in it. you can easily manage it in code

Categories

Resources