Excel parameter in t/sql SELECT TOP xxx without using SP - tsql

This is really only a short question, but I can't find the answer anywhere.
Is it possible to use an Excel parameter in a t/sql query as a SELECT TOP xxxx, where the parameter here defines how many rows are fetched, without using a stored procedure?

From sql 2005 and up you can write your query as:
Enter the following in your msquery:
{CALL sp_executesql (N'select top (#a) * from mytable', N'#a int', ?)}

I'm not sure about applying the Excel parameter, but to do this in T-SQL do:
select *
from (
select row_number() over (order by [Field]) as rowNum, *
from [myTable] ) s
where s.rowNum < #maxRows

If you are in Excel can you not use Concat to build up the sql query?
Concatenate("select top ", $D2, " from mytable where...")
and use the value of that cell as your tsql expression?
http://msdn.microsoft.com/en-us/library/aa188518(v=office.10).aspx

Related

Pivot function without manually typing values in `for in`?

Documentation provides an example of using the pivot() function.
SELECT *
FROM (SELECT partname, price FROM part) PIVOT (
AVG(price) FOR partname IN ('prop', 'rudder', 'wing')
);
I would like to use pivot() without having to manually specify each value of partname. I want all parts. I tried:
SELECT *
FROM (SELECT partname, price FROM part) PIVOT (
AVG(price) FOR partname);
That gave an error. Then tried:
SELECT *
FROM (SELECT partname, price FROM part) PIVOT (
AVG(price) FOR partname IN (select distinct partname from part)
);
That also threw an error.
How can I tell Redshift to include all values of partname in the pivot?
I don't think this can be done in a simple single query. This would mean that the query compiler would need to work without knowing how many output columns will be produced. I don't think it can do that.
You can do this in multiple queries - use a query to create the list of partnames and then use this to "generate" a second query that populates the IN list. So something needs issue these queries and generated the second. This can be some code external to Redshift (lots of options) or a stored procedure in Redshift. This code, no matter where it exists, should understand that Redshift has a max number of columns limit - 1,600.
The Redshift docs are fairly good on the topic of dynamic SQL for stored procedures. The EXECUTE statement will be used to fire off the second query in a stored procedure. See: https://docs.aws.amazon.com/redshift/latest/dg/c_PLpgSQL-statements.html

Db2 convert rows to columns

I need the below results ..
Table :
Order postcode qnty
123 2234 1
Expected result:
Order 123
Postcode 2234
Qnty 1
SQL server:
Select pvt.element_name
,pvt.element_value(select order.postcode
from table name)up
unpivot (element_value for element_name in(order,postcode) as Pvt
How to achieve this in db2?
Db2 for IBM i doesn't have a built-in unpviot function.. AFAIK, it's not available on any Db2 platofrm...unless it's been added recently.
The straight forward method
select 'ORDER' as key, order as value
from mytable
UNION ALL
select 'POSTCODE', postcode
from mytable
UNION ALL
select 'QNTY', char(qnty)
from mytable;
A better performing method is to do a cross join between the source table and a correlated VALUES of as many rows as columns that need to be unpivoted.
select
Key, value
from mytable T,
lateral (values ('ORDER', t.order)
, ('POSTCODE', t.postcode)
, ('QNQTY', varchar(t.qnty))
) as unpivot(key, value);
However, you'll need to know ahead of time what the values you're unpivoting on.
If you don't know the values, there are some ways to unpivot with the XMLTABLE (possibly JSON_TABLE) that might work. I've never used them, and I'm out of time to spend answering this question. You can find some examples via google.
I have created a stored procedure for LUW that rotate a table:
https://github.com/angoca/db2tools/blob/master/pivot.sql
You just need to call the stored procedure by passing the tablename as parameter, and it will return a cursor with the headers of the column in the first column.

How to return a comma separated string using Crystal SQL Expression

I want to display a string on each row (Details section) in my Crystal Report. The contents of this string will be retrieved with the help of a SQL Expression.
The SQL I have is follows: However if multiple rows are returned, I am not sure how to convert that into a Comma Separated String. I have an Oracle 11g database.
(select distinct NAME from TEST
where SAMPLE_NUMBER = "TEST"."SAMPLE_NUMBER"
and X_BENCH <> '"TEST"."X_BENCH"')
The TEST Table looks like this:
My report will be filtered for all samples with a specific test (e.g. Calcium). For those samples on the report, My SQL Expression should retrieve all "Other" Tests on the sample. See output example.
You can accomplish this with a wm_concat. WM_CONCAT takes a bunch of rows in a group and outputs a comma separated varchar.
Using the substr function you can separate the first result with the last.
Please note that I am dirty coding this (without a compiler to check my syntax) so things may not be 100% correct.
select sample_number
, substr(wm_concat(name),1,instr(wm_concat(name),",")-1) as NAME
, substr(wm_concat(name),instr(wm_concat(name),","),length(wm_concat(name)-instr(wm_concat(name),",")+1) as OTHER_TEST_NAMES
from TEST
where SAMPLE_NUMBER = "TEST"."SAMPLE_NUMBER"
and X_BENCH <> '"TEST"."X_BENCH"'
and rownum < 2
group by sample_number
However, if it is not necessary to separate the name and the other test names, it actually is much simpler.
select sample_number
, wm_concat(name) as NAMES
from TEST
where SAMPLE_NUMBER = "TEST"."SAMPLE_NUMBER"
and X_BENCH <> '"TEST"."X_BENCH"'
and rownum < 2
group by sample_number
Also please try to organize your lines to make it easier to read.
You can use LISTAGG for Converting Rows to Comma-Separated String in Oracle.
Example:
SELECT user_id
, LISTAGG(expertise, ',')
WITHIN GROUP (ORDER BY expertise)
AS expertise
FROM TEMP_TABLE
GROUP BY user_id;

Line numbering in result grid in MySQL Workbench

Is there any way to add some line numbers in the result grid in MySQL Workbench?
E.g. (red numbers):
I don't want to have to change the SQL query, which I know I can do using tricks like
SELECT #n := #n + 1 `Number of Submissions`, t.*
FROM (SELECT #n:=0) initvars,
( SELECT COUNT(*) AS count
FROM moocdb.submissions
GROUP BY user_id
ORDER BY count DESC
) t
I also don't want to have to export the results.
Not sure if that is a good question for SO, but anyway: no this is not possible. Nobody asked for that so far, so, file a feature request at http://bugs.mysql.com to have that in.
MySQL does not provide row_number like Microsoft SQL Server, Oracle, or PostgreSQL. Fortunately, MySQL provides session variables that you can use to emulate the row_number function.
SET #row_number = 0;
SELECT (#row_number:=#row_number + 1) AS num, col_1
FROM
Table

Differences between Dates in MSSQL

I have a situation where I need to get the differences between two columns.
Column 1: 01-OCT-13 10:27:15
Column 2: 01-OCT-13 10:28:00
I need to get the differences between those above two columns. I tried using '-' operator but the output is not in an expected way.
I need output as follows: 00-00-00 00:00:45
I can get it in Oracle using MOD function. But I am not sure about SQL Server.
You can use DATEDIFF
SELECT DATEDIFF(ss,startDate,endDate)
SQL FIDDLE
DATEDIFF
drop table #t1
create table #t1(clo1 datetime,col2 datetime)
insert into #t1 values('01-OCT-13 10:27:15','01-OCT-13 10:28:00')
select cast((col2-clo1) as time) from #t1
See Demo
Try the following
SELECT DATEDIFF (datepart, Column 1,Column 2)
Values for datepart:
mi : minute
ss,s: second
So,
SELECT DATEDIFF (s, Column 1,Column 2)
Refer this for more