Transpose a single row multiple columns into multiple rows single colum - sql

I have a table valued function in sql server which returns multiple rows and single column such as below
1
2
3
I use the syntax select * from dbo.function to use the values returned by this function in where clause of my queries.
Now apart from the value returned by the function I want to put certain hard coded values in that where clause.
For example :
Select * from dbo.table where ID in (Select * from dbo.function + **I want to add some more values here**)
So that if function returns
1
2
3
I want to add lets say
4
5
in that list such that final query becomes as follows :
select * from dbo.table where ID in (1,2,3,4,5)

Use or:
Select *
from dbo.table
where ID in (Select * from dbo.function) or
ID in (4, 5)
Although you could mangle the subquery using union all, the above makes the query easier to follow (in my opinion). Also, in the event that "function" is really a table, it is easier for the optimizer to recognize appropriate indexes.

Related

How to merge data of two tables with different column name in Big Query

How can I get final output based on table 1 and table 2 in Big Query
Table 1
Table 2
Final Output
You can use union all. If the columns are in the same order:
select *
from table1
union all
select *
from table2;
In general, though, it is better to list out the column names instead of using *. Note that in the result set, the names from the first select are used for the result set.

How to select top multiple of 10 entries?

How to select top multiple of 10 entries?
I have a data in SQL table that is meaningful if only seen as bunch of 10 entries. I want to write a query that does this for ex. Select top 10*n from table where condition.
If for ex. 53 entries satisfy condition, I want only 50 to be seen and last 3 to be discarded.
Plz help.
Kbv
How about:
declare #rows int;
set #rows = ((select count(*) from table where condition)/10)*10
select top #rows * from table where condition
Try this:
with CTE AS (
SELECT * FROM Table WHERE Condition
)
Select top(((SELECT COUNT(*) FROM CTE)/10)*10) * From CTE
Please consider the following...
SELECT orderField,
field1,
...
FROM tblTable
WHERE condition
ORDER BY orderField
LIMIT 10 * numberOfGroups;
When constructing your query first decide which fields you want. In a simple one table query you can use SELECT * fairly safely, but if you are referring to a JOINed dataset then you should consider specifying which fields you are going to use and assigning aliases to those fields.
Make sure that whatever your orderField or orderFields are called they are covered by a wildcard such as * or by being explicitly specified.
The above code first selects all records that meet your criteria. It then sorts the resulting list based upon which field or fields you specify for ORDER BY. Note : The above assumes that you are sorting based upon existing values in your table. If you need to sort based on computed values then another (minor) level of complexity may need to be added.
LIMIT will then grab the first specified number of records from the sorted list. LIMIT accepts simply computed values such as 2 * 2 or 10 * numberOfGroups, where numberOfGroups is a variable set previously in the code or a value that explicitly replace numberOfGroups (i.e. 10 * #numberOfGroups where #numberOfGroups has previously been set to 5 or 10 * 5).
If you have any questions or comments, then please feel free to post a Comment accordingly.

how do i filter a column with multiple values

how do i filter a column col1 with multiple values
select * from table where col1=2 and col1=4 and userID='740b9738-63d2-67ff-ba21-801b65dd0ae1'
i tired
select * from table where col1=2 or col1=4 and userID='740b9738-63d2-67ff-ba21-801b65dd0ae1'
the result of both queries is incorrect
the first one gives zero results
second one gives 3 results
the correct is 2 results
the sql will run against the sqlite db.
AND is evaluated before OR, so your query is equivalent to:
select *
from table
where col1=2 or (col1=4 and userID='740b9738-63d2-67ff-ba21-801b65dd0ae1')
You need to explicitly group the conditions when mixing AND and OR:
select *
from table
where (col1=2 or col1=4) and userID='740b9738-63d2-67ff-ba21-801b65dd0ae1'

Assistance with SQL statement

I'm using sql-server 2005 and ASP.NET with C#.
I have Users table with
userId(int),
userGender(tinyint),
userAge(tinyint),
userCity(tinyint)
(simplified version of course)
I need to select always two fit to userID I pass to query users of opposite gender, in age range of -5 to +10 years and from the same city.
Important fact is it always must be two, so I created condition if ##rowcount<2 re-select without age and city filters.
Now the problem is that I sometimes have two returned result sets because I use first ##rowcount on a table. If I run the query.
Will it be a problem to use the DataReader object to read from always second result set? Is there any other way to check how many results were selected without performing select with results?
Can you simplify it by using SELECT TOP 2 ?
Update: I would perform both selects all the time, union the results, and then select from them based on an order (using SELECT TOP 2) as the union may have added more than two. Its important that this next select selects the rows in order of importance, ie it prefers rows from your first select.
Alternatively, have the reader logic read the next result-set if there is one and leave the SQL alone.
To avoid getting two separate result sets you can do your first SELECT into a table variable and then do your ##ROWCOUNT check. If >= 2 then just select from the table variable on its own otherwise select the results of the table variable UNION ALLed with the results of the second query.
Edit: There is a slight overhead to using table variables so you'd need to balance whether this was cheaper than Adam's suggestion just to perform the 'UNION' as a matter of routine by looking at the execution stats for both approaches
SET STATISTICS IO ON
Would something along the following lines be of use...
SELECT *
FROM (SELECT 1 AS prio, *
FROM my_table M1 JOIN my_table M2
WHERE M1.userID = supplied_user_id AND
M1.userGender <> M2.userGender AND
M1.userAge - 5 >= M2.userAge AND
M1.userAge + 15 <= M2.userAge AND
M1.userCity = M2.userCity
LIMIT TO 2 ROWS
UNION
SELECT 2 AS prio, *
FROM my_table M1 JOIN my_table M2
WHERE M1.userID = supplied_user_id AND
M1.userGender <> M2.userGender
LIMIT TO 2 ROWS)
ORDER BY prio
LIMIT TO 2 ROWS;
I haven't tried it as I have no SQL Server and there may be dialect issues.

Returning more than one value from a sql statement

I was looking at sql inner queries (bit like the sql equivalent of a C# anon method), and was wondering, can I return more than one value from a query?
For example, return the number of rows in a table as one output value, and also, as another output value, return the distinct number of rows?
Also, how does distinct work? Is this based on whether one field may be the same as another (thus classified as "distinct")?
I am using Sql Server 2005. Would there be a performance penalty if I return one value from one query, rather than two from one query?
Thanks
You could do your first question by doing this:
SELECT
COUNT(field1),
COUNT(DISTINCT field2)
FROM table
(For the first field you could do * if needed to count null values.)
Distinct means the definition of the word. It eliminates duplicate returned rows.
Returning 2 values instead of 1 would depend on what the values were, if they were indexed or not and other undetermined possible variables.
If you are meaning subqueries within the select statement, no you can only return 1 value. If you want more than 1 value you will have to use the subquery as a join.
If the inner query is inline in the SELECT, you may struggle to select multiple values. However, it is often possible to JOIN to a sub-query instead; that way, the sub-query can be named and you can get multiple results
SELECT a.Foo, a.Bar, x.[Count], x.[Avg]
FROM a
INNER JOIN (SELECT COUNT(1) AS [Count], AVG(something) AS [Avg]) x
ON x.Something = a.Something
Which might help.
DISTINCT does what it says. IIRC, you can SELECT COUNT(DISTINCT Foo) etc to query distinct data.
you can return multiple results in 3 ways (off the top of my head)
By having a select with multiple values eg: select col1, col2, col3
With multiple queries eg: select 1 ; select "2" ; select colA. you would get to them in a datareader by calling .NextRecord()
Using output parameters, declare the parameters before exec the query then get the value from them afterwards. eg: set #param1 = "2" . string myparam2 = sqlcommand.parameters["param1"].tostring()
Distinct, filters resulting rows to be unique.
Inner queries in the form:
SELECT * FROM tbl WHERE fld in (SELECT fld2 FROM tbl2 WHERE tbl.fld = tbl2.fld2)
cannot return multiple rows. When you need multiple rows from a secondary query, you usually need to do an inner join on the other query.
rows:
SELECT count(*), count(distinct *) from table
will return a dataset with one row containing two columns. Column 1 is the total number of rows in the table. Column 2 counts only distinct rows.
Distinct means the returned dataset will not have any duplicate rows. Distinct can only appear once usually directly after the select. Thus a query such as:
SELECT distinct a, b, c FROM table
might have this result:
a1 b1 c1
a1 b1 c2
a1 b2 c2
a1 b3 c2
Note that values are duplicated across the whole result set but each row is unique.
I'm not sure what your last question means. You should return from a query all the data relevant to the query. As for faster, only benchmarking can tell you which approach is faster.