Am a front-end dev. Let's get that out of the way... My issue is I need to get some data out of a few tables within the DB. The backend is written in C#. (I will try to answer questions on it if need be) which is not my area.
My SQL is just about average, I can understand enough to write the query that I need see below:
(I've sanitized the table names)
SELECT *
FROM (SELECT * FROM table_1 UNION SELECT * FROM table_2) name
JOIN (SELECT OrderNo, ID FROM table_3 UNION SELECT OrderNo, ID from table_4) name_2
ON name.OrderNo = name_2.OrderNo
WHERE name_2 = <queryParam>
The difficult part is that I need to be able to run this query by varying search terms, by order number, by telephone number and by branch ID using linq.
Can anyone help and also point me in the direction of (preferably easy) resources to learn?
Related
When my query is:
select * from table_name where name='jim'
everything is fine.
But when my query is:
select * from table where ='a statement with 2 and more word'
For example this query:
select columns from table where ='jim carrey'
The query just considers 'jim'. In other words, the query just considers the first word and does not consider whatever comes after that.
SQL does not work like that. If you take the following three queries:
select * from users where name = 'Frank Jones'
select * from users where name = 'Frank'
select * from users where name like 'Frank%'
If I run these on my SQL server database (after changing back to our real data structure) I will get 1 response to the first , the person who is actually named "Frank Jones'. I will not get 'Frank Jones III'
Since both first and last names are in the name columns if I run the second query, I will get no results.
If I run the third query I will get everyone whose first name if Frank but will not get "Jason Franks' because I only have a wildcard at the end of the phrase I am searching for. If I wanted everyone who had and portion of Frank in their name I would write this query:
select * from users where name like '%Frank%'
These are standard rules on what the various where clauses mean that apply to every database I have ever seen (although some might have a differnt wildcard symbol).
You don't say what platform you are using which makes answering your question harder but I will give an answer that will be close.
You need to parse the first work in the string. So
SELECT aColumn
FROM aTable
WHERE name = LEFT('Jim Carrey', CHARINDEX('Jim Carrey',' '))
Would be an example in sql server
The name of these functions changes for each platform.
I am not sure if I titled this question correctly, here is my question. I have a table that has Products and these products have various details including buying price, selling price, initial stock quantity, number of items sold, number of items remaining. I then have another table with sales information based on location of the buyer lets call it LocationSales. I need to create a table that will show the products and the location information like in the snapshot below.
I made the representation using Excel. I had already achieved this while working on a project earlier last year but it involved a lot or hard-coding and stack-overflow exceptions. I would like to achieve this more effectively. This is a hypothetical representation of my actual problem. I have tried using hierarchical tables before using Telerik UI which worked well but did not display the information quite as required by my superiors. I would really appreciate it if someone would point me to the right direction. I understand it's impossible to address the entire problem here but I would appreciate someone including a link to a blog post or video or some literature that can assist me. PS. I have tried database views as well, didn't work as required.
I am using ASP.NET C# MVC5 with Visual Studio 2013 and the database as SQL Server 2012
EDIT://Tables I am using
EDIT 2:///
As per my research so far i have managed to obtain the following
SQL CODE://
select * from
(select
locationName
,productName as [PRODUCT]
,roadTransfer
,airTransfer
,initialQty
,soldQty
,remQty
from
Location as l inner join
Sales as s on l.locationID=s.locationID
inner join
Product as p on p.productID=s.productID
)as BaseData
pivot(
count(roadTransfer)
for locationName
in([Germany]
,[Kenya]
) as SummaryTable
order by Product asc
I used a pivot table. I am currently trying to get both the road and air transfer. I I will try using a GROUP BY clause and see what I can do. I will post an update when I have the full solution.
So at this point (Edit 2) you have created a pivot for road transfer. Unfortunately you can't aggregate more than one value in a pivot, so the way round it is to do two pivots and join the results together. You result set therefore has 3 query parts to produce the query
A list of products
Pivoted Road Transfer amounts by country
Pivoted Air Transfer amounts by country
If you left join all of them together in a single query on the product ID you will get close to your query, but the column order won't be quite right i.e. all the Road Transfers will come before the Air Transfers.
I have created a SQLFiddle demonstrating this
Select p.prodName AS Product,
p.initialQty AS [Initial Quantity],
p.sold AS [Quantity Sold],
p.remaining AS [Quantity Remaining],
AirT.[Air Transfer - Germany],
RoadT.[Road Transfer - Germany],
AirT.[Air Transfer - Kenya],
RoadT.[Road Transfer - Kenya]
FROM Products p
LEFT JOIN (
SELECT productID, [Germany] AS [Air Transfer - Germany], [Kenya] AS [Air Transfer - Kenya]
FROM (select productID, l.locName, qty
FROM sales s
INNER JOIN Locations l on l.locID = s.locID
where transfer = 'Air Transfer') as SourceTable
PIVOT (SUM(qty)
FOR locName IN ([Germany], [Kenya])
) As AirTransfers
) AirT on AirT.productID = p.ProductID
LEFT JOIN (
SELECT productID, [Germany] AS [Road Transfer - Germany], [Kenya] AS [Road Transfer - Kenya]
FROM (select productID, l.locName, qty
FROM sales s
INNER JOIN Locations l on l.locID = s.locID
where transfer = 'Road Transfer') as SourceTable
PIVOT (SUM(qty)
FOR locName IN ([Germany], [Kenya])
) As RoadTransfers
) RoadT on RoadT.productID = p.ProductID
Today I encountered problem that causes difficulty for me to solve it.
In application I want to display records in aphabetical order thus in SQL statement I'am using ORDER BY, But it looks like CAPITAL letters are before lowercase letters so record starting with Z is before a.
This is example of my sql statement
SELECT * FROM myTable WHERE id= 5 ORDER BY name
Do you have any ideas ? Can I sort data in DataTable object after retreiving it from database ? or can it be accomplished by more complex sql statement?
Any ideas will be appreciated
You can modify your SQL query in such a way that all capitals are transformed to lower before ordering
SELECT * FROM myTable WHERE id = 5 ORDER BY LOWER(name)
The rules for comparing text values is the collation; there are many many collations available in SQL Server, and most have both case-sensitive and case-insensitive options.
If you don't want to change the collation (in particular, if this applies only to specific cases), you can also use functions like LOWER / UPPER, but this cannot make efficient use of indexes. A hybrid approach is to store redundant information: store the original data in one column, and the standardized data (perhaps all lower-case-invariant) in a second column. Then you can index the two separately (as you need), and operate on either the original or standardized data. You would normally only display the original data, though. Persisted+calculated+indexed columns might work well here, as then it is impossible to get inconsistent data (the server is in charge of the calculated column).
Try
SELECT * FROM myTable WHERE id= 5 ORDER BY LOWER(name)
OR
SELECT * FROM myTable WHERE id= 5 ORDER BY LCASE(name)
depending on which database you are using
You can perform ordering by providing case in SQL. Just do this:
SELECT * FROM myTable WHERE id= 5 ORDER BY UPPER(name)
OR
SELECT * FROM myTable WHERE id= 5 ORDER BY UCASE(name)
Ordering will be done on upper case name while you result will be same as present in table.
Try this...
SELECT * FROM myTable WHERE id= 5 ORDER BY name COLLATE Latin1_General_100_CI_AS
I have a database that contains:
user_id | category_id | liked_id | disliked_id
(thanks to stack overflow users for helping me get my database setup properly in the first place!!)
Last time I used food as an example but this time I'm going to use people.
The user is given 2 images (male vs male or female vs female) and he/she simply chooses which one he/she thinks is more attractive. The user repeats this process as long as he/she wishes. Each selection is entered into the database showing which person they liked and which they disliked (also a button would be available if you think the two are similar).
Now that I have my table full of entries, I'm trying to develop an algorithm that will take all of those "votes" and translate it into a ranked list of who the user finds most attractive (based on hundreds or maybe even thousands of ranking entries).
I've been at the drawing board for hours and can't seem to think of an effective way of doing this.
Any help would be appreciated.
P.S.: The idea is also to have this be a multi-user thing, where other users can see your "like" tables and also have globally averaged tables showing how all users in general rank things.
So you posted your question in the c# group. I want to give you, however, a solution that is implemented in the database, making it more independent of your program.
What you probably want to do first is to get the number of times an image has been liked and disliked. This SQL statement should do that for you (if you are using a database supporting grouping sets it would probably be easier to write):
SELECT t1.liked_id as id, t1.c_liked, t2.c_disliked
FROM
(SELECT liked_id, COUNT(*) as c_liked FROM table GROUP BY liked_id) t1
LEFT JOIN
(SELECT disliked_id, COUNT(*) c_disliked FROM table GROUP BY disliked_id) t2
ON
t1.liked_id = t2.disliked_id
Then it's up to you what you do with the numbers. In the outermost SELECT-statement, you could put a very complicated function, e.g. you could choose to weigh the dislikes less than the likes. To give you an idea of a possible very simple function:
SELECT t1.liked_id as id,
(t1.c_liked/(t1.c_liked + t2.c_disliked) - t2.c_disliked/(t1.c_liked + t2.c_disliked)) as score
This returns you values [-1, 1] (which you could normalize to [0, 1] if you like, but don't have to), which you then can sort as in this example:
SELECT t1.liked_id as id,
(t1.c_liked/(t1.c_liked + t2.c_disliked) - t2.c_disliked/(t1.c_liked + t2.c_disliked)) as score
FROM
(SELECT liked_id, COUNT(*) as c_liked FROM table GROUP BY liked_id) t1
LEFT JOIN
(SELECT disliked_id, COUNT(*) c_disliked FROM table GROUP BY disliked_id) t2
ON
t1.liked_id = t2.disliked_id
ORDER BY score
I have a linq query which selects several fields from my Customer table.
Applied to this method are multiple filters, using Func<IQueryable<T>, IQueryable<T>> with .Invoke.
The original query is essentially select * from customer.
The filter method is essentially select top 10
The output SQL is select top 10 from (select * from customer)
My customer table has over 1,000,000 rows which causes this query to take about 7 seconds to execute in SSMS. If I alter the output SQL to select top 10 from (select top 10 * from customer) by running it in SSMS then the query is instant (as you'd expect).
I am wondering if anyone knows what might cause LINQ to not combine these in a nice way, and if there is a best practice/workaround I can implement.
I should note that my actual code isn't select * it is selecting a few fields, but there is nothing more complex.
I am using SQL Server 2008 and MVC 3 with entity framework (not sure what version)
Edit: I should add, it's IQueryable all the way, nothing is evaluated until the end, and as a result the long execution is confined to that single line.
I don't know why it's not being optimised.
If the filter method really is equivalent to SELECT TOP 10 then you should be able to do it like this:
return query.Take(10);
which would resolve to select top 10 * from customer rather than the more convoluted thing you ended up with.
If this won't work then I'm afraid I'll need a little more detail.
EDIT: To clarify, if you do this in LINQ:
DataItems.Take(10).Take(10)
you would get this SQL:
SELECT TOP (10) [t1].[col1], [t1].[col2]
FROM (
SELECT TOP (10) [t0].[col1], [t0].[col2]
FROM [DataItem] AS [t0]
) AS [t1]
So if you can somehow use a Take(n) you will be okay.