Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a query where I iterate through a table -> for each entry I iterate through another table and then compute some results. I use a cursor for iterating through the table. This query takes ages to complete. Always more than 3 minutes. If I do something similar in C# where the tables are arrays or dictionaries it do... | The problem is that you're trying to use a set-based language to iterate through things like a procedural language. SQL requires a different mindset. You should almost never be thinking in terms of loops in SQL.
From what I can gather from your code, this should do what you're trying to do in all of those loops, but i... | You might not even need documents
```
INSERT INTO QueryScores (id, score)
SELECT W.DocumentId as [id]
, SUM(W.[Weight] + Q.[Weight]) as [score]
FROM Query Q
JOIN TfidfWeights W
ON W.StemId = Q.StemId
AND W.[Weight] > 0
GROUP BY W.DocumentId
``` | SQL Query with Cursor optimization | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have an author table
| au\_id | au\_fname | au\_lname | city | state |
what i am trying to do is get a query of first and last names based on who lives in the same state as Sarah
Heres what I have so far:
```
SELECT AU_FNAME, AU_LNAME FROM authors WHERE "STATE" like 'CA'
```
I don't want to use a static state in... | Use a `Sub-Query` to find the state of `Sarah` and filter that `state`
Try this
```
SELECT AU_FNAME, AU_LNAME
FROM authors
WHERE STATE in (select state from authors where au_fname = 'Sarah')
``` | ```
SELECT AU_FNAME, AU_LNAME FROM authors WHERE STATE in (select state from authors where au_fname = 'sarah')
```
or
```
select a1.AU_FNAME, a1.AU_LNAME FROM authors a1
inner join authors a2 on a1.state = a2.state
where a2.au_fname = 'sarah'
``` | Select * from a table using data from specific entry in table | [
"",
"sql",
""
] |
unfortunately i'm not that good as SQL and i'm trying to get a join between three tables done.
here's a rough simplified table structure:
```
links: id, url, description
categories: id, name, path
link_cat: link_id, cat_id
```
The select statement I'm aiming for should have
```
links.id, link.url, link.description,... | ```
SELECT links.id, links.url, links.description, categories.name, categories.path
FROM links
INNER JOIN link_cat ON links.id = link_cat.links_id
INNER JOIN categories ON categories.id = link_cat.category_id
``` | ```
# Add each field you want to the select list
SELECT links.id, link.url, link.description, categories.name, categories.path
# Add the "links" table to the list of tables to select from
FROM links
# Add the "link_cat" table, specify "link_id" as the common field
JOIN link_cat USING (link_id)
# Add the "categories"... | Join three (3) MySQL tables | [
"",
"mysql",
"sql",
"join",
""
] |
**SCHEMA**
I have the following set-up in MySQL database:
```
CREATE TABLE items (
id SERIAL,
name VARCHAR(100),
group_id INT,
price DECIMAL(10,2),
KEY items_group_id_idx (group_id),
PRIMARY KEY (id)
);
INSERT INTO items VALUES
(1, 'Item A', NULL, 10),
(2, 'Item B', NULL, 20),
(3, 'Item C', NULL, 30),
(... | According to [this answer](https://stackoverflow.com/a/28090544/3549014) by [@axiac](https://stackoverflow.com/users/4265352/axiac), better solution in terms of compatibility and performance is shown below.
It is also explained in [SQL Antipatterns book, Chapter 15: Ambiguous Groups](https://rads.stackoverflow.com/amz... | You can do this using `where` conditions:
`SQLFiddle Demo`
```
select t.*
from t
where t.group_id is null or
t.price = (select min(t2.price)
from t t2
where t2.group_id = t.group_id
);
```
Note that this returns all rows with the minimum price, if there is more... | Group only certain rows with GROUP BY | [
"",
"mysql",
"sql",
"group-by",
"greatest-n-per-group",
""
] |
Imagine the following two tables, named "Users" and "Orders" respectively:
```
ID NAME
1 Foo
2 Bar
3 Qux
ID USER ITEM SPEC TIMESTAMP
1 1 12 4 20150204102314
2 1 13 6 20151102160455
3 3 25 9 20160204213702
```
What I want to get as the output is:
```
USER ITEM SP... | The best way i can think of is using `OUTER APPLY`
```
SELECT *
FROM Users u
OUTER apply (SELECT TOP 1 *
FROM Orders o
WHERE u.ID = o.[USER]
ORDER BY TIMESTAMP DESC) ou
```
Additionally creating a below `NON-Clustered` Index on `ORDERS` table wi... | This should do the trick :
```
SELECT Users.ID, Orders2.USER , Orders2.ITEM , Orders2.SPEC , Orders2.TIMESTAMP
FROM Users
LEFT JOIN
(
SELECT Orders.ID, Orders.USER , Orders.ITEM , Orders.SPEC , Orders.TIMESTAMP, ROW_NUMBER()
OVER (PARTITION BY ID ORDER BY TIMESTAMP DESC) AS... | LEFT OUTER JOIN and only return the first match | [
"",
"sql",
"sql-server",
"left-join",
"outer-join",
""
] |
I am receiving an error message for this one. The error message is:
> Data type varchar of receiving variable is not equal to the data type
> nvarchar of column 'VEHICLE\_ID2\_FW'
Please help, thanks
```
DECLARE @IMPORTID INT
DECLARE @LASTID INT
DECLARE @VEHICLEID VARCHAR (20)
SELECT @LASTID = (SELECT LAST_REFERENC... | Try changing your script with this script below
```
DECLARE @IMPORTID INT
DECLARE @LASTID INT
DECLARE @VEHICLEID VARCHAR (20)
SELECT @LASTID = (SELECT LAST_REFERENCE_FW FROM REFERENCE_FW WHERE RECORD_TYPE_FW like N'VEHICLES_ORDERS_FW' AND REFERENCE_FIELD_FW LIKE N'VEHICLE_ID2_FW' AND ARCHIVE_STATUS_FW LIKE N'N')
SE... | Mabey here is the problem:
```
set @LASTID = VEHICLES_ORDERS_FW.VEHICLE_ID2_FW = @LASTID + 1
```
will be good if you provide table structure. | Data type varchar of receiving variable is not equal to the data type nvarchar of column | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have 2 tables,
Table 1 is fact\_table
```
style sales
ABC 100
DEF 150
```
and Table 2 is m\_product
```
product_code style category
ABCS ABC Apparel
ABCM ABC Apparel
ABCL ABC Apparel
DEF38 DEF Shoes
DEF39 DEF Shoes
DEF40 DE... | use a sub-query:
```
Select t1.style, t2.category, t1.sales
From fact_table t1
Inner Join (SELECT DISTINCT style, category FROM m_product) t2
On t1.style = t2.style
```
BTW, you need to change the DB design to move the category to a separate table | Maybe something like this:
```
select p.style, p.category, f.sales
(select distinct style, category
from m_product) p join fact_table f
on p.style = f.style
``` | Join in SQL Server with several data | [
"",
"sql",
"sql-server",
""
] |
I have a scenario whereby the `accountNo` is not a `Primary Key` and it has duplicates and I would like to search for accounts that have `priority` with the value of `'0'`. The `priority` field is a `varchar` data type. The following table is an example:
```
ID AccountNo Priority
1 20 0
2 22 0
3 ... | If `Priority` field takes only values in `('0', '1')`, then try this:
```
SELECT AccountNo
FROM CustTable
GROUP BY AccountNo
HAVING MAX(Priority) = '0'
```
otherwise you can use:
```
SELECT AccountNo
FROM CustTable
GROUP BY AccountNo
HAVING COUNT(CASE WHEN Priority <> '0' THEN 1 END) = 0
``` | This would work regardless of the RDBMS you use, as not all of them accept a 'group by' without selecting an aggregate function (e.g. max()).
It'd be better if you mention the RDBMS you use, going forward.
```
SELECT DISTINCT tmp.AccountNo
FROM
(SELECT AccountNo, MAX(Priority)
FROM CustTable
GROUP BY Acco... | Finding specific values in SQL | [
"",
"sql",
""
] |
For my website, I have a loyalty program where a customer gets some goodies if they've spent $100 within the last 30 days. A query like below:
```
SELECT u.username, SUM(total-shipcost) as tot
FROM orders o
LEFT JOIN users u
ON u.userident = o.user
WHERE shipped = 1
AND user = :user
AND... | You would need to take the following steps (per user):
* join the *orders* table with itself to calculate sums for different (bonus) starting dates, for any of the starting dates that are in the last 30 days
* select from those records only those starting dates which yield a sum of 100 or more
* select from those reco... | The following is basically how to do what you want. Note that references to "30 days" are rough estimates and what you may be looking for is "29 days" or "31 days" as works to get the exact date that you want.
1. Retrieve the list of dates and amounts that are still active, i.e., within the last 30 days (as you did in... | Finding date where conditions within 30 days has elapsed | [
"",
"mysql",
"sql",
"date",
""
] |
I would like to get distinct record of each Design and type with random id of each record
It is not possible to use
```
select distinct Design, Type, ID from table
```
It will return all values
This is structure of my table
```
Design | Type | ID
old chair 1
old table 2
old chair 3
new chair 4
new table 5
new table ... | If it doesn't matter which one, you can always take the maximum\minimum one:
```
SELECT design,type,max(ID)
FROM YourTable
GROUP BY design,type
```
This won't be randomly, it will always take the maximum\minimum one but it doesn't seems like it matters. | Hope this one helps you :
```
WITH CTE AS
(
SELECT Design, Type, ID, ROW_NUMBER() OVER (PARTITION BY Design,
Type ORDER BY id DESC) rid
FROM table
)
SELECT Design, Type, ID FROM CTE WHERE rid = 1 ORDER BY ID
``` | select distinct two columns with random id | [
"",
"sql",
"random",
"db2",
"distinct",
""
] |
How sort this
```
a 1 15
a 2 3
a 3 34
b 1 55
b 2 44
b 3 8
```
to (by third column sum):
```
b 1 55
b 2 44
b 3 8
a 1 15
a 2 3
a 3 34
```
since (55+44+8) > (15+3+34) | If you are using SQL Server/Oracle/Postgresql you could use windowed `SUM`:
```
SELECT *
FROM tab
ORDER BY SUM(col3) OVER(PARTITION BY col) DESC, col2
```
`LiveDemo`
Output:
```
βββββββ¦βββββββ¦βββββββ
β col β col2 β col3 β
β ββββββ¬βββββββ¬βββββββ£
β b β 1 β 55 β
β b β 2 β 44 β
β b β 3 β 8 β
β a ... | You can do this using ANSI standard window functions. I prefer to use a subquery although this is not strictly necessary:
```
select col1, col2, col3
from (select t.*, sum(col3) over (partition by col1) as sumcol3
from t
) t
order by sumcol3 desc, col3 desc;
``` | sql sorting by subgroup sum data | [
"",
"sql",
"sorting",
"group-by",
""
] |
I want to extract all of the string after, and including, 'Th' in a string of text (column called 'COL\_A' and before, and including, the final full stop (period). So if the string is:
```
'3padsa1st/The elephant sat by house No.11, London Street.sadsa129'
```
I want it to return:
```
'The elephant sat by house No.1... | Assuming that the full stop is given by the last period in you string, you can try with something like this:
```
select regexp_substr('3padsa1st/The elephant sat by house No.11, London Street.sadsa129',
'(Th.*)\.')
from dual
``` | From [the INSTR docs](http://docs.oracle.com/database/121/SQLRF/functions089.htm#SQLRF00651), you can use a negative value of `position` to search backwards from the end of the string, so this returns the position of the last full stop:
```
instr (cola, '.', -1)
```
So you can do this:
```
substr ( cola
, ins... | Extract string after character and before final full stop (/period) in SQL | [
"",
"sql",
"string",
"oracle",
"plsql",
""
] |
I need to generate a text file and inside generate the employee name and the length should 20. eg, if the name length is above 20 display only first 20 characters, if the name length is below 20, first display the name and leading character fill with blank space (left aligned).
I tried the following example
**1)**
... | The one with `left` is almost correct, except that you have to add spaces after the string, not before:
```
select
left(CONVERT(NVARCHAR, 'Merbin Joe') + replicate(' ', 20), 20)
``` | Try this:
```
SELECT LEFT(CONVERT(NVARCHAR, 'Merbin Joe') + SPACE(20), 20)
``` | How to restrict the character when the length is out of 20 characters in sql | [
"",
"sql",
"sql-server",
""
] |
I have an Oracle SQL query which includes calculations in its column output. In this simplified example, we're looking for records with dates in a certain range where some field matches a particular thing; and then for those records, take the ID (not unique) and search the table again for records with the same ID, but ... | Looking ***only*** at restructuring the existing query *(rather that logically or functionally different approaches)*.
The simplest approach, to me, for is simply to do this as a nested query...
- The inner query would be your basic query, without the CASE statement
- It would also include your correlated sub-quer... | You can do it without correlated sub-queries or sub-query factoring (`WITH .. AS ( ... )`) clauses using an analytic function (and in a single table scan):
```
SELECT ID,
EarliestDateOfAnotherThing
FROM (
SELECT ID,
MIN( CASE WHEN SomeField = 'Another Thing' THEN SomeFieldDate END )
OVER... | Oracle SQL: Re-use subquery for CASE WHEN without having to repeat subquery | [
"",
"sql",
"oracle",
"subquery",
"code-reuse",
""
] |
I have a table where several reporting entitities store several versions of their data (indexed by an integer version number). I created a view for that table that selects only the latest version:
```
SELECT * FROM MYTABLE NATURAL JOIN
(
SELECT ENTITY, MAX(VERSION) VERSION FROM MYTABLE
GROUP BY ENTITY
)
```
Now... | You could avoid the self-join with an analytic query:
```
SELECT ENTITY, VERSION, LAST_VERSION
FROM (
SELECT ENTITY, VERSION,
NVL(LAG(VERSION) OVER (PARTITION BY ENTITY ORDER BY VERSION), VERSION) AS LAST_VERSION,
RANK() OVER (PARTITION BY ENTITY ORDER BY VERSION DESC) AS RN
FROM MYTABLE
)
WHERE RN = 1;
``... | You can formulate the task as: Get the two highest available versions per entity and from these take the minimum version per entity. You determine the n highest versions by ranking the records with `ROW_NUMBER`.
```
select entity, min(version)
from
(
select
entity,
version,
row_number() over (partitio... | Oracle SQL: select max minus 1 except lowest (get previous data version) | [
"",
"sql",
"oracle",
""
] |
I just wonder how to use below MySQL query in laravel5.2 using eloquent.
```
SELECT MAX(date) AS "Last seen date" FROM instances WHERE ad_id =1
```
I have column date in instance table .
I would like to select the latest date from that table where ad\_id =1 | If you want to get the `date` column only then use the following:
```
$instance = Instance::select('date')->where('ad_id', 1)->orderBy('date', 'desc')->first();
```
Or if you want to get all the instances related to that latest date then use:
```
$instance = Instance::where('ad_id', 1)->orderBy('date', 'desc')->get(... | To actually select the max though you can now:
```
Instance::latest()->get();
```
Documentation: [laravel.com/docs/5.6/queries](https://laravel.com/docs/5.6/queries) | max(date) sql query in laravel 5.2 | [
"",
"sql",
"laravel-5",
"eloquent",
"max",
""
] |
I'm trying to get a row count from a record set.
What I would like is to count the number of rows in the record-set, grouped by a common value in a column named `member_location`, ordered by a column named `reputation_total_points` in descending order, until the parser reaches a result with a specific value in the `ID... | If I understood correctly this should work as expected:
```
SELECT rn
FROM
(
SELECT id
,ROW_NUMBER() -- assign a sequence based on descending order
OVER (ORDER BY reputation_total_points DESC) AS rn
FROM tab
WHERE member_location = 10
) AS dt
WHERE id = 2 -- find the matching id
```
In fact th... | I am not sure your where works with both id and member\_location, as the id = 2 will only bring back one row. However if you're just after the occurences where member\_location = 10 then something like the below should work:
```
SELECT
member_location,
COUNT(member_location) AS [Total]
FROM yourTable
GROUP B... | RECORD COUNT in SQL with an ORDER BY, until a specific value is found in a column | [
"",
"sql",
"vbscript",
"asp-classic",
"sql-server-2012",
""
] |
i have full date(with time).
But i want only millisecond from date.
please tell me one line solution
for example: `date= 2016/03/16 10:45:04.252`
i want this answer= `252`
i try to use this query.
```
SELECT ADD_MONTHS(millisecond, -datepart('2016/03/16 10:45:04.252', millisecond),
'2016/03/16 10:45:04.252') F... | > i have full date (with time)
This can only be done using a `timestamp`. Although Oracle's `date` does contain a time, it only stores seconds, not milliseconds.
---
To get the fractional seconds from a **timestamp** use `to_char()` and convert that to a number:
```
select to_number(to_char(timestamp '2016-03-16 10... | ```
SELECT
TRUNC((L.OUT_TIME-L.IN_TIME)*24) ||':'||
TRUNC((L.OUT_TIME-L.IN_TIME)*24*60) ||':'||
ROUND(CASE WHEN ((L.OUT_TIME-L.IN_TIME)*24*60*60)>60 THEN ((L.OUT_TIME-L.IN_TIME)*24*60*60)-60 ELSE ((L.OUT_TIME-L.IN_TIME)*24*60*60) END ,5) Elapsed
FROM XYZ_TABLE
``` | How to extract millisecond from date in Oracle? | [
"",
"sql",
"oracle11g",
"timestamp",
""
] |
How to covert the following `11/30/2014` into `Nov-2014`.
`11/30/2014` is stored as varchar | A solution that should work even with Sql server 2005 is using [convert](https://msdn.microsoft.com/en-us/library/ms187928(v=sql.90).aspx), [right](https://msdn.microsoft.com/en-us/library/ms177532(v=sql.90).aspx) and [replace](https://msdn.microsoft.com/en-us/library/ms186862(v=sql.90).aspx):
```
DECLARE @DateString ... | Try it like this:
```
DECLARE @str VARCHAR(100)='11/30/2014';
SELECT FORMAT(CONVERT(DATE,@str,101),'MMM yyyy')
```
The `FORMAT` function was introduced with SQL-Server 2012 - very handsome...
Despite the tags you set you stated in a comment, that you are working with SQL Server 2012, so this should be OK for you... | Conversion function to convert the following "11/30/2014" format to Nov-2014 | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I have this SQL at the moment:
```
SELECT Count(create_weekday),
create_weekday,
Count(create_weekday) * 100 / (SELECT Count(*)
FROM call_view
WHERE
( create_month = Month(Now() -
INTERVAL 1 month) )
AND ( crea... | Use ROUND(Percentage, 1):
```
SELECT Count(create_weekday),
create_weekday,
ROUND(Count(create_weekday) * 100 / (SELECT Count(*)
FROM call_view
WHERE
( create_month = Month(Now() -
INTERVAL 1 month) )
AND ( cre... | You can just use the built-in `ROUND(N,D)` function, the second argument is the number of digits.
MySQL Reference: <http://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_round> | Calculate group percentage to 1 decimal places - SQL | [
"",
"mysql",
"sql",
""
] |
I need make a query that I get the result and put in one line separated per comma.
For example, I have this query:
```
SELECT
SIGLA
FROM
LANGUAGES
```
This query return the result below:
**SIGLA**
```
ESP
EN
BRA
```
I need to get this result in one single line that way:
**SIGLA**
```
ESP,EN,BRA
```
Can an... | try
```
SELECT LISTAGG( SIGLA, ',' ) within group (order by SIGLA) as NewSigla FROM LANGUAGES
``` | ```
SELECT LISTAGG(SIGLA, ', ') WITHIN GROUP (ORDER BY SIGLA) " As "S_List" FROM LANGUAGES
```
Should be the listagg sequence you are needing | Group query rows result in one result | [
"",
"sql",
"oracle",
""
] |
I've been looking all around stack overflow and can't seem to find a question like this but its probably super simple and has been asked a million times. So I am sorry if my insolence offends you guys.
I want to remove an attribute from the result if it appears anywhere in the table.
Here is an example: I want displa... | You can use NOT EXISTS() :
```
SELECT DISTINCT s.team
FROM Players s
WHERE NOT EXISTS(SELECT 1 FROM Players t
where t.team = s.team
and position = 'Pitcher')
```
Or with NOT IN:
```
SELECT DISTINCT t.team
FROM Players t
WHERE t.team NOT IN(SELECT s.team FROM Players s
... | Use `NOT EXISTS`
**Query**
```
select distinct team
from players p
where not exists(
select * from players q
where p.team = q.team
and q.position = 'Pitcher'
);
``` | Removing an item from the result if it has a particular parameter somewhere in the table | [
"",
"mysql",
"sql",
""
] |
I want to calculate the average of a column of numbers, but i want to exclude the rows that have a zero in that column, is there any way this is possible?
The code i have is just a simple sum/count:
```
SELECT SUM(Column1)/Count(Column1) AS Average
FROM Table1
``` | ```
SELECT AVG(Column1) FROM Table1 WHERE Column1 <> 0
``` | One approach is `AVG()` and `CASE`/`NULLIF()`:
```
SELECT AVG(NULLIF(Column1, 0)) as Average
FROM table1;
```
Average ignores `NULL` values. This assumes that you want other aggregations; otherwise, the obvious choice is filtering. | How to calculate an average in SQL excluding zeroes? | [
"",
"sql",
""
] |
I have a problem how can we write sql statement in this:
I have this:
```
id name color
1 A blue
3 D pink
1 C grey
3 F blue
4 E red
```
and I want my result to be like this:
```
id name name color ... | **Query - Concatenate the values into a single column**:
```
SELECT ID,
LISTAGG( Name, ',' ) WITHIN GROUP ( ORDER BY ROWNUM ) AS Names,
LISTAGG( Color, ',' ) WITHIN GROUP ( ORDER BY ROWNUM ) AS Colors
FROM table_name
GROUP BY ID;
```
**Output**:
```
ID Names Colors
-- ----- ---------
1 A,C blue,g... | there is a fundamental problem with what you are trying to achieve - you do not know how many values of names (/ color) per id to expect - so you do not know how many columns the output should be.....
a workaround would be to keep all the names (and colors) per id in one column :
```
select id,group_concat(name),group... | How write sql statement to have in one line the same ID | [
"",
"sql",
"database",
"oracle",
""
] |
I am currently working with a SQL back end and vb.net Windows Forms front end. I am trying to pull a report from SQL based on a list of checkboxes the user will select.
To do this I am going to use an `IN` clause in SQL. The only problem is if I use an if statement in vb.net to build the string its going to be a HUGE ... | First you need to set up all your checkboxes with the Tag property set to the line number to which they refers. So, for example, the CBLine1 checkbox will have its property Tag set to the value 1 (and so on for all other checkboxes).
This could be done easily using the WinForm designer or, if you prefer, at runtime in... | I feel that I'm only half getting your question but I hope this helps. In VB.net we display a list of forms that have a status of enabled or disabled.
There is a checkbox that when checked displays only the enabled forms.
```
SELECT * FROM forms WHERE (Status = 'Enabled' or @checkbox = 0)
```
The query actually has ... | Build string for SQL statement with multiple checkboxes in vb.net | [
"",
"sql",
"vb.net",
"string",
"if-statement",
""
] |
I have an SQL Server table were each row represent a machine log that says the time when the machine were switched on or switched off. The columns are ACTION, MACHINE\_NAME, TIME\_STAMP
ACTION is a String that can be "ON" or "OFF"
MACHINE\_NAME is a String representing the machine id
TIME\_STAMP is a date.
An example... | I was able to solve this using CTEs and the `LAG` function. This enables us to get the first `'ON'` action for each `'OFF'`, and thereafter apply `ROW_NUMBER` to match them:
```
;WITH first_ON AS
(
SELECT *, LAG(m.ACTION, 1, 'OFF') OVER (PARTITION BY m.MACHINE_NAME ORDER BY m.TIME_STAMP) AS previous_action
FR... | You can do it with a correlated query like this:
```
SELECT t.Machine_name,
t.time_stamp as start_date,
(SELECT min(s.time_stamp) from YourTable s
WHERE t.Machine_name = s.Machine_Name
and s.ACTION = 'OFF'
and s.time_stamp > t.time_stamp) as end_date
FROM YourTable t
WHERE t.a... | Extracting start and end date in groups | [
"",
"sql",
"sql-server",
""
] |
I have a string such as this:
```
`a|b^c|d|e^f|g`
```
and I want to maintain the pipe delimiting, but remove the carrot sub-delimiting, only retaining the first value of that sub-delimiter.
The output result would be:
```
`a|b|d|e|g`
```
Is there a way I can do this with a simple SQL function? | Another option, using [`CHARINDEX`](https://msdn.microsoft.com/en-us/library/ms186323(v=sql.90).aspx), [`REPLACE`](https://msdn.microsoft.com/en-us/library/ms186862(v=sql.90).aspx) and [`SUBSTRING`](https://msdn.microsoft.com/en-us/library/ms187748(v=sql.90).aspx):
```
DECLARE @OriginalString varchar(50) = 'a|b^c^d^e|... | This expression will replace the first instance of caret up to the subsequent pipe (or end of string.) You can just run a loop until no more rows are updated or no more carets are found inside the function, etc.
```
case
when charindex('^', s) > 0
then stuff(
s,
charindex('^', s),
... | SQL Remove string between two characters | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2005",
""
] |
Please, this is my sql script
```
#-- creation de la table user
CREATE TABLE IF NOT EXISTS user(
iduser int AUTO_INCREMENT,
nom VARCHAR(50) NOT NULL,
prenom VARCHAR(50) ,
adressemail VARCHAR(200) NOT NULL,
motdepasse VARCHAR(200) NOT NULL,
CONSTRAINT pk_user PRIMARY KEY(iduser)
);
#-- creation de la tabl... | In your foreign key constraint you have set the action on delete to `set null`, but the column `user_iduser` does not allow null values as it is specified as `not null` which makes the constraint invalid. Either change the column to allow null values or change the delete action in the constraint.
The online MySQL manu... | Your statement `ON DELETE SET NULL` is restricting you to create table as your column `user_iduser` cannot be NULL as you written
```
user_iduser INT NOT NULL
``` | Can't create table 'mydb.contact' (errno: 150) | [
"",
"mysql",
"sql",
"mariadb",
"mariasql",
""
] |
I'm trying to include default values for data that is grouped but outside of the where statement.
**Table**
```
Name Location
-----------------------
Chris North
John North
Jane North-East
Bryan South
```
**Query**
```
SELECT
Location,
COUNT(*)
FROM Users
WHERE Location = 'North' OR Location =... | I think the simplest way is to use conditional aggregation:
```
SELECT Location,
SUM(CASE WHEN Location IN ('North', 'North-East') THEN 1 ELSE 0 END) as cnt
FROM Users u
GROUP BY Location;
```
Or, better yet, if you have a locations table:
```
select l.location, count(u.location)
from locations l left join
... | Assuming there is no locations table, the only way to do this is to do DISTINCT and a sub select
```
SELECT DISTINCT
Location,
(SELECT COUNT(*) FROM users AS U
WHERE U.Name = Users.Name
AND Location = 'North' OR Location = 'North-East')
FROM Users
WHERE Location = 'North' OR Location = 'North-E... | GroupBy Return Results Outside of Restriction | [
"",
"sql",
"sql-server",
""
] |
I am trying to return the number of years someone has been a part of our team based on their join date. However i am getting a invalid minus operation error. The whole `getdate()` is not my friend so i am sure my syntax is wrong.
Can anyone lend some help?
```
SELECT
Profile.ID as 'ID',
dateadd(year, -profile.J... | **MySQL Solution**
Use the `DATE_DIFF` function
> The DATEDIFF() function returns the time between two dates.
>
> DATEDIFF(date1,date2)
<http://www.w3schools.com/sql/func_datediff_mysql.asp>
This method only takes the number of days difference. You need to convert to years by dividing by 365. To return an integer, ... | Looks like you're using T-SQL? If so, you should use DATEDIFF:
```
DATEDIFF(year, profile.JOIN_DATE, getdate())
``` | Subtract table value from today's date - SQL | [
"",
"sql",
"subtraction",
"getdate",
""
] |
I have been really struggling with this one! Essentially, I have been trying to use COUNT and GROUP BY within a subquery, errors returning more than one value and whole host of errors.
So, I have the following table:
```
start_date | ID_val | DIR | tsk | status|
-------------+------------+--------+-----+-----... | You want one result per `ID_val`, so you'd group by `ID_val`.
You want the minimum start date: `min(start_date)`.
You want any status (as it is always the same): e.g. `min(status)` or `max(status)`.
You want to count matches: `count(case when <match> then 1 end)`.
```
select
min(start_date) as start_date,
id_va... | This is a basic conditional aggregation:
```
select id_val,
sum(case when (dir = 'U' and tsk = 28) or (dir = 'D' and tsk = 56)
then 1 else 0
end) as NumTimes
from t
group by id_val;
```
I left out the other columns because your question focuses on `id_val`, `dir`, and `tsk`. The othe... | SQL Server - COUNT with GROUP BY in subquery | [
"",
"sql",
"sql-server",
""
] |
[Here](https://stackoverflow.com/q/5653423/383688) I've found how to define a variable in Oracle SQL Developer.
But can we define the range of values somehow?
I need smth like this:
```
define my_range = '55 57 59 61 67 122';
delete from ITEMS where ITEM_ID in (&&my_range);
``` | Actually if you put commas in your list it will work since you are using a substitution parameter (not a bind variable):
```
define my_range = '55, 57, 59, 61, 67, 122';
delete from ITEMS where ITEM_ID in (&&my_range);
```
[](https://i.stack.imgur.c... | Use a collection:
```
CREATE TYPE INT_TABLE AS TABLE OF INT;
/
```
Then you can do:
```
DEFINE my_range = '55,57,59,61,67,122';
DELETE FROM items
WHERE ITEM_ID MEMBER OF INT_TABLE( &&my_range );
```
**Example**:
```
CREATE TABLE ITEMS ( ITEM_ID ) AS
SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 150;
DEFINE my_ran... | Can we define a variable which contains the range of values in Oracle SQL Developer? | [
"",
"sql",
"oracle",
"range",
""
] |
I need help with a sql query. I have a table like this:
```
ID bookType Date
----------- ---------- ------
1 85 01.01.2014
1 86 01.01.2014
1 88 01.01.2014
1 3005 01.01.2014
1 3028 01.01.2014
2 74 01.01.2016
2 ... | I see some inconsistency between your SQL and your columns names.
There is no bookid in the table and you miss booktype...
So assuming your first query is:
```
SELECT ID AS ID, COUNT(ID) AS number FROM books WHERE date
BETWEEN '2014-01-01' and '2016-01-01' and bookType in (85,86)
GROUP BY ID
HAVING COUNT(ID) >1;
```... | Try this:
```
SELECT bookid AS id, COUNT(*) AS number
FROM books
WHERE date BETWEEN DATE '2014-01-01' and DATE '2016-01-01'
GROUP BY bookid
HAVING COUNT(DISTINCT CASE WHEN booktype IN (85,86) THEN booktype END) = 2 AND
COUNT(CASE WHEN booktype IN (88, 3005, 3028) THEN 1 END) = 0
```
If you just want to count... | How to select id's which contains just special values? | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
"having",
""
] |
```
student_mas:: receipt_mas
name class name class month
john 2nd john 2nd JAN
bunny 3rd john 2nd FEB
sunny 4th bunny 3rd FEB
```
student who submits fees for a particular m... | You can use **`NOT EXISTS`**
**Query**
```
select * from student_mas t
where not exists (
select * from receipt_mas
where name = t.name
and class = t.class
and [month] = 'JAN'
);
```
**`SQL Fiddle demo`** | Ullas answer would work perfectly but you can try like the below approach.
```
DECLARE @student_mas TABLE (
NAME VARCHAR(50)
,class VARCHAR(10)
);
insert into @student_mas
values
('john', '2nd'),
('bunny', '3rd'),
('sunny', '4th');
DECLARE @receipt_mas TABLE (
NAME VARCHAR(50)
,class VARCHAR(10)... | There are two tables. i want to join them in such a way that i can get the following result | [
"",
"sql",
"sql-server",
"vb.net",
"visual-studio-2010",
""
] |
I am working on a join and I cannot seem to get the resultset that I need. Let me paint the scenario:
I have 2 tables:
Data table
```
+----+-------+
| ID | Name |
+----+-------+
| 10 | Test1 |
| 11 | Test2 |
| 12 | Test3 |
| 13 | Test4 |
| 14 | Test5 |
| 15 | Test6 |
+----+-------+
```
Join table
```
+----+-----+... | The expression **`C.FID <> null`** will never evaluate to true, it will always return NULL. An inequality comparison to `NULL` will always evaluate to `NULL`. (In SQL, in a boolean context, en expression will evaluate to one of *three* possible values: `TRUE`, `FALSE` or `NULL`.)
If you want a comparison to `NULL` to ... | ```
SELECT
*
FROM datatable A
LEFT JOIN jointable B ON A.ID = B.ID
WHERE B.FID = 3 OR B.GID = 1;
```
This will return you:
```
10 Test1 10 3 abc
10 Test1 10 1 def
11 Test2 11 3 ijk
12 Test3 12 1 lmn
```
Now, it seems you want to filter out:
```
10 Test1 10 3 abc
``... | Two joins in mysql query not returning expected result | [
"",
"mysql",
"sql",
"join",
"resultset",
""
] |
I'm trying to select all client ID's that has `TypeId` equal 1 but not `TypeId` equal 3.
Table example:
```
---------------------
| ClientID | TypeId |
---------------------
| 1 | 1 |
| 1 | 3 |
| 2 | 3 |
| 3 | 1 |
---------------------
```
My query:
```
SELECT ClientI... | I would suggest aggregation and `having`:
```
SELECT ClientId
FROM Table
GROUP BY ClientId
HAVING SUM(CASE WHEN TypeId = 1 THEN 1 ELSE 0 END) > 0 AND
SUM(CASE WHEN TypeId = 3 THEN 1 ELSE 0 END) = 0;
```
Each condition in the `HAVING` clause counts the number of rows having a particular `TypeId` value. The `> 0... | Try this:
```
SELECT t1.*
FROM Table AS t1
WHERE TypeId = 1 AND
NOT EXISTS (SELECT 1
FROM Table AS t2
WHERE t1.ClientId = t2.ClientId AND t2.TypeId = 3)
``` | SQL Query with group and having | [
"",
"sql",
"sql-server",
"performance",
""
] |
I have 2 tables:
* `tbl1(ID, Name, Sex, OrderDate)`
* `tbl2(OrderDate, OrderCode)`
I try to display all data from `tbl1 (ID, Name, Sex, OrderDate)` and **only** one column from `tbl2(OrderCode)`.
I have tried this
```
SELECT tbl1.*, tbl2.OrderCode FROM tbl1, tbl2;
```
but it shows duplicate data. like this
](https://i.stack.imgur.com/edxsZ.png)
and then use this query
```
select t1.ID, t1.Name, t1.Sex, t2.OrderDate, t2.OrderCode from
Table1 t1
inner join Table2 t2 on t1.ID = t2.ID;
``` | You are doing a CROSS JOIN which results in a cartesian product
You should JOIN on the field that is common in the 2 tables to limit the rows returned.
In your case the only field I see on both tables is OrderDate, and that's a bit weird.
Try this
```
SELECT tbl1.*, tbl2.OrderCode FROM tbl1, tbl2 WHERE tbl1.OrderDa... | Ms.Access query in vb.net select all from tbl1 and only 1 column from tbl2 | [
"",
"sql",
"vb.net",
"ms-access",
""
] |
```
table 1
id name value activ
1 abc 5 1
2 def 6 1
3 ghi 10 0
4 jkl 15 1
table 2
id name value table1_id
1 abc 100 1
2 jkl 200 4
```
i want to return all records from table 1 where active = 1 and the records from table 2 where table1\_id refer... | **[SQL Fiddle Demo](http://sqlfiddle.com/#!9/ae959/2)**
```
SELECT T1.name,
COALESCE(T2.value, T1.value) as value
FROM Table1 as T1
LEFT JOIN Table2 as T2
ON T1.id = T2.table1_id
WHERE T1.active = 1
```
**OUTPUT**
```
| name | value |
|------|-------|
| abc | 100 |
| jkl | 200 |
| def | 6 |... | ```
SELECT a.name,
NVL(b.value, a.value)
FROM table1 a
LEFT OUTER JOIN table2 b
ON a.id =b.table1_id
WHERE a.activ=1;
``` | mysql - not in statement | [
"",
"mysql",
"sql",
"notin",
""
] |
I do not understand why mysql says that there is unknown column in where clause. If I remove alias and just use log\_archive.date then it works just fine.
Here is the sql:
```
SELECT DISTINCT(log_archive.msisdn) AS msisdn,
DATE(log_archive.date) AS actionDate,
users.activation_date
FROM log_arc... | Column alias name can't be used in `WHERE` clause.
# Reference:
<http://dev.mysql.com/doc/refman/5.7/en/problems-with-alias.html>
> Standard SQL disallows references to column aliases in a WHERE clause.
> This restriction is imposed because when the WHERE clause is
> evaluated, the column value may not yet have been... | Because your actionDate is not a aliased name of column, actionDate is a aliase of the result of function `DATE`
If change the sql as below, it's still working, so problem is not the aliased name, you must use the exactly column in where clause.
```
SELECT DISTINCT(log_archive.msisdn) AS msisdn,
log_archive.da... | Mysql aliased column unknown in the where clause | [
"",
"mysql",
"sql",
""
] |
I have an `updates` table in Postgres is 9.4.5 like this:
```
goal_id | created_at | status
1 | 2016-01-01 | green
1 | 2016-01-02 | red
2 | 2016-01-02 | amber
```
And a `goals` table like this:
```
id | company_id
1 | 1
2 | 2
```
I want to create a chart for each company that shows t... | You need one data item per week and goal (before aggregating counts per company). That's a plain `CROSS JOIN` between `generate_series()` and `goals`. The (possibly) expensive part is to get the current `state` from `updates` for each. Like [@Paul already suggested](https://stackoverflow.com/a/36088907/939860), a `LATE... | This seems like a good use for `LATERAL` joins:
```
SELECT EXTRACT(ISOYEAR FROM s) AS year,
EXTRACT(WEEK FROM s) AS week,
u.company_id,
COUNT(u.goal_id) FILTER (WHERE u.status = 'green') AS green_count,
COUNT(u.goal_id) FILTER (WHERE u.status = 'amber') AS amber_count,
COUNT(u.... | Aggregating the most recent joined records per week | [
"",
"sql",
"postgresql",
"greatest-n-per-group",
""
] |
I need to link 2 tables in one big table.
My problem is that I need to link 2 different columns (in example: books, toys) in one column (things).
Other columns:
* if they are in both tables, then they are in one column in every row (in example: price)
* if they are in one table, then in rows with data from other table... | You can try using a `UNION ALL` more info [here](http://www.techonthenet.com/sql/union_all.php)
Something like this:
```
SELECT books "things", NULL "name", cover, price
FROM table1
UNION ALL
SELECT toys "things", name , NULL "cover", price
FROM table2
``` | How about a simple UNION:
```
select books as things, null as name, cover, price
from table1
union
select toys as things, name, null as cover, price from table2
``` | SQL: linking two different columns in one | [
"",
"sql",
""
] |
I have two tables:
* `customers` table, with columns `customer_id`, `created_at`
* `orders` table, with columns `order_id`, `customer_id`, `paid_at`, `amount`
I have to write a SQL query that breaks up the customers based on the year that they signed up (their cohort year), and determines total annual revenue for eac... | GROUP BY year ( date column )
```
select c.customer_id, YEAR(c.created_at), SUM(o.amount) as Tot_amt
from customers c inner join orders o on c.customer_id = o.customer_id
group by c.customer_id, YEAR(c.created_at)
``` | To support your statement
> 2011 cohort has total revenue of $x in year 1, $y in year 2
you should have orderDate in your orders table
```
select
YEAR(c.created_at) as cohortYear,
(YEAR(orderDate)-YEAR(c.created_at)+1) as YearNum,
SUM(o.amount) OVER( PARTITION by YEAR(c.created_at),(YEAR(orderDate)-YEAR(c.create... | Need sum of a fact row grouped by start year and every year after it | [
"",
"mysql",
"sql",
"sql-server",
""
] |
I am new to regular expression. I am using regular expression in SQL query. And want to display all the records which contain anything other than: Alphanumeric characters, white spaces, hyphen(-) in between the string, dot(.)in the end and in between the string.
I have been able to do for alphanumeric characters and sp... | I tried a whole lot of solutions. Finally the below is exactly working the way i wanted.
```
SELECT * FROM my_table WHERE (INSTR(column1,'.', 1, 1))=1
or (INSTR(column1,'-', 1, 1))=1 or (INSTR(column1,'-', 1,1)=length(column1))
or (REGEXP_LIKE(column1,'[^[:alnum:]^[:blank:]-.]'));
``` | I've create table just like yours and this statement
```
select * from tmp where x like '.%' OR x like '-%' or x like '%-';
```
works perfectly fine - only . and -
:) | what will be the regular expression for allowing alphanumeric characters, space, hypen in between, dot at the end or in between | [
"",
"sql",
"regex",
"oracle",
""
] |
First of all I have this which returns the date of all the football games where
HomeShotsOnTarget(HST) = FullTimeHomeGoals(FTHG)
or
AwayShotsOnTarget(AST) = FullTimeAWayGoals(FTHG)
```
SELECT MatchDate, HomeTeam, AwayTeam
FROM matches
WHERE HST=FTHG or AST=FTAG
```
**This displays**
```
MatchDate | HomeTeam | A... | You just have to join the Team-Table two times, try this query:
```
SELECT
MatchDate,
T1.RealName,
T2.RealName
FROM
matches INNER JOIN club T1 ON (matches.HomeTeam = T1.TeamCode)
INNER JOIN club T2 ON (matches.AwayTeam = T2.TeamCode)
WHERE
HST=FTHG OR AST=FTAG
``` | Maybe something like:
```
SELECT MatchDate, homeTeam.RealName AS HomeTeam, awayTeam.RealName AS AwayTeam
FROM matches m
INNER JOIN club homeTeam ON (m.HomeTeam = homeTeam.TeamCode)
INNER JOIN club awayTeam ON (m.AwayTeam = awayTeam.TeamCode);
```
I use to put some meaning labels instead of just, `T1` and `T2`. | MySQL - displaying two inner joins in separate columns | [
"",
"mysql",
"sql",
"database",
"join",
"inner-join",
""
] |
I have two config tables. The structure is as below:
```
Table 1: Client_Config
id, name, value, type, description
Table 2: App_Config
name, value, type, description
```
I want to get `name` and `value` from `Client_config` table **`where id = @id`**.
I also want to get `name` and `values` from `App_config` for row... | You can do it using a left join:
```
SELECT t.id, s.name, s.value, s.type, s.description
FROM App_Config s
LEFT JOIN Client_Config t
ON(t.name = s.name and t.id = @id)
``` | You can try a query like below
```
select
c.id, a.name, a.value, a.type, a.description
from App_Config a
left join
(
select * from Client_Config where id=@id
)c
on c.name=a.name
```
**Explanation:** We need all rows from `app_config` and corresponding id from `client_config`. So we do a `**LEFT JOIN**` from A... | Joining two tables and getting values | [
"",
"sql",
"sql-server",
"sql-server-2008",
"join",
""
] |
I could do
```
select substr(to_char(20041111), 1, 4) FROM dual;
2004
```
Is there a way without converting to string first? | You can use the [FLOOR function](http://docs.oracle.com/database/121/SQLRF/functions076.htm#SQLRF00643):
```
select floor(20041111/10000) from dual;
``` | The following does not convert to a string but I'm not sure it's more readable...:
```
select floor(20041111 / power(10, floor(log(10, 20041111) - 3)))
from dual;
```
log(10, 20041111) -> 8.3... meaning that 10 ^ 8.3... = 20041111
if you floor this value, you get the number of digits in the base 10 representation of... | How to get first 4 digits in a number, with oracle sql | [
"",
"sql",
"oracle",
""
] |
Hi i want to search for a particular string in a table stored in mysql database. The table structure is as follow:-
```
+--------------------------------------------------------------------------+
| day | 9-10 | 10-11 | 11-12 | 12-1 | 1-2 | 2-3 | 3-4 |
|--------------------------------------------... | ```
SELECT * from `table` where day='Thursday' AND (`9-10`='DA6220' OR `10-11`='DA6220' OR `11-12`='DA6220'
OR `12-1`='DA6220' OR `1-2`='DA6220' OR `2-3`='DA6220' OR `3-4`='DA6220')
```
Looks like your AND is evaluated first. Please try the above | The answer to your problem has been given, but when I look at your data I see something that can make your life a lot easier and increase your possibilities:
You would better to create a **VIEW**.
First of all, I have adapted slightly your columns names because you had reserved words.
[Click here for SQL Fiddle](http... | SQL query to search for string in a table? | [
"",
"mysql",
"sql",
"database",
""
] |
I Need to Extract the Date from Address column Value . It may be possible that my address column value may have street no , house no , city , state , country, day etc
But I want to extract only City value or state value or country value . How can i extract that particular if all values are stored in one address column... | You Need to make some changes that it will work good .
So While entering data in Address Column you need to maintain a structure Everytime you insert data maintain that structure then you can select your desired result with query below -
```
SELECT Mid(Title, Instr(Title, 'Day') + 4, Instr(Title, '|')- Instr(Title, '... | I created this. It will separate all your values. You forgot to mention the `Area` so I added it also.
`SQLFiddle Demo`
```
select
substring_index(substring_index(Address, ',', 1),',',-1) as street_no,
substring_index(substring_index(Address, ',', 2),',',-1) as house_no,
substring_index(substring_index(A... | How do I display a part of column Value in sql? | [
"",
"mysql",
"sql",
""
] |
I am learning databases and I am using SQL Server 2008. When I go through the concept of join, I found the problem of duplication of data on table. I tried to avoid duplicate values by using distinct keyword but it's not working. I show you my table structure, query which I am trying and required output. Thank you in a... | You can not get that output as you described. Because using left or right outer join also not get the desired output.
I tried this :
```
select distinct i.Item_Name, g.GrpName
from ItemMaster i right outer join GrpDetail g
on i.Id = g.Id
order by i.Item_Name, g.GrpName;
```
And also tried :
```
select distinct i.I... | If you only want the "first" row to get a match, then you can use `row_number()`. Here is one way without a subquery:
```
SELECT T2.ItemName,
(CASE WHEN ROW_NUMBER() OVER (PARTITION BY T2.ItemName ORDER BY ID) = 1
THEN T1.GroupName
END) as GroupName
FROM TABLE2 T2 JOIN
TABLE1 T1
... | How to avoid duplicate values during joining of 2 table using SQL Server 2008 | [
"",
"sql",
"sql-server-2008",
""
] |
I want to get the specific row data.
but in this query it shows me the error.In here i want to get 5th row
> ORA-00904: "RN": invalid identifier
Code
```
SELECT NEWSDATE,ROWNUM AS RN
FROM NEWS
WHERE NEWSNO='100000' AND (CAT='LR' OR CRT ='LD') AND RN = 5 //<-- It highlighted this RN is invalid
ORDER BY N... | Try this:
```
select * from (
SELECT NEWSDATE,row_number() over (order by newsdate) AS RN
FROM NEWS
WHERE NEWSNO='100000' AND (CAT='LR' OR CRT ='LD')
)
where rn = 5;
``` | You can't use column aliases defined in the `SELECT` clause in the `WHERE` clause as the `WHERE` clause is evaluated first. To make your query syntactically valid it would be:
```
SELECT NEWSDATE,ROWNUM AS RN
FROM NEWS
WHERE NEWSNO='100000' AND (CAT='LR' OR CRT ='LD') AND ROWNUM = 5
ORDER BY NEWSDATE ASC
```
... | Get the specific row data on Oracle | [
"",
"sql",
"oracle",
""
] |
I have a sql view, let's call it `SampleView`, whose results have the following format.
```
Id (INT), NameA (VARVHAR(50)), NameB (VARCHAR(50)), ValueA (INT), ValueB (INT)
```
The result set of the view contains rows that may have the same `Id` or not. When there are two or more rows with the same Id, I would like to ... | You can use window functions:
```
SELECT DISTINCT
id,
FIRST_VALUE(NameA) OVER (PARTITION BY id
ORDER BY len(NameA) DESC) AS MaxNameA,
MAX(ValueA) OVER (PARTITION BY id) AS MaxValueA,
FIRST_VALUE(NameB) OVER (PARTITION BY id
... | You can use correlated queries like this:
```
SELECT
t.Id,
(SELECT TOP 1 s.NameA FROM SampleView s
WHERE s.id = t.id
ORDER BY length(s.NameA) DESC) as NameA,
(SELECT TOP 1 s.NameB FROM SampleView s
WHERE s.id = t.id
ORDER BY length(s.NameB) DESC) as NameB,
MAX(t.ValueA),
MAX(t.... | tsql group by get alphanumeric column value with maximum length | [
"",
"sql",
"sql-server",
"sql-server-2012",
"group-by",
"max",
""
] |
So I have a dataset where I want to select the closest records to point X for my output,
What I have is
```
PROC SQL ;
create table Check_vs_Excel2 as
SELECT PROPERTY, START_DATE, END_DATE, DAY_OF_WEEK, MARKET_CODE_PREFIX, RATE_PGM, ROOM_POOL, QUOTE_SERIES_NO, QUOTE_POSITION
FROM Sbtddraf.Vssmauditdraftful... | In SQL your query would be using a Correlated Subquery:
```
SELECT PROPERTY, START_DATE, END_DATE, DAY_OF_WEEK, MARKET_CODE_PREFIX, RATE_PGM, ROOM_POOL, QUOTE_SERIES_NO, QUOTE_POSITION
FROM Sbtddraf.Vssmauditdraftfull AS t
-- group by Property, RATE_PGM
WHERE START_DATE =
( select MAX(START_DATE)
FROM Sbtddraf... | Assuming I understand that you want the row that has the minimum absolute difference between start\_date and today() (so, `MIN(ABS(START_DATE-TODAY()))`), you can do a somewhat messy query using the having clause this way:
```
data have;
do id = 2 to 9;
do start_date = '02MAR2016'd to '31MAR2016'd by id;
o... | How to select within the closest thing to Y in SAS as a starting point | [
"",
"sql",
"sas",
"proc-sql",
""
] |
my supervisor asked me to not put transactions and commit etc in this code because he says that it's useless to put transactions in this procedure. He's well experienced and i can't directly argue with him so need your views on it ?
```
ALTER PROCEDURE [Employee].[usp_InsertEmployeeAdvances](
@AdvanceID B... | ```
ALTER PROCEDURE [Employee].[usp_InsertEmployeeAdvances]
(
@AdvanceID BIGINT,
@Employee_ID INT,
@AdvanceDate DATETIME,
@Amount MONEY,
@MonthlyDeduction MONEY,
@Balance MONEY,
@SYSTEMUSER_ID INT,
@EntryDateTime DATETIME = NULL,
... | This is a changed answer as I did not read the whole question
Without a transaction if this was called at the same time and record did not exists then both could insert and one would likely get @Balance wrong
yes a transaction serves a purpose | Is it necessary to put transactions in this code? | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
"t-sql",
""
] |
I have a column `Time` in my table. It holds a time value in minutes, ie: 605. What I want it to show it as 10:05, as `hh:mm` format.
I am doing it like this:
```
...
Time = cast(AVG(Time) / 60 as varchar) + ':' + cast(AVG(Time) % 60 as varchar),
...
```
It shows the value as 10:5, but I want to make it as 10:05 and... | You can use a `case` expression to do this.
Also you should always specify the length of varchar when you use `cast`, or it would only show the first character.
```
case when len(cast(AVG(Time)%60 as varchar(2))) < 2 then '0'+cast(AVG(Time)%60 as varchar(2))
else cast(AVG(Time)%60 as varchar(2))
end
``` | Try this:
```
SELECT
TIME = CASE WHEN @t < 600 THEN '0' ELSE '' END +
CAST(Time / 60 as varchar(10)) + ':' +RIGHT(100 +(Time % 60), 2)
```
Example:
```
DECLARE @t int = 55121
SELECT
TIME = CASE WHEN @t < 600 THEN '0' ELSE '' END +
CAST(@t / 60 as varchar(10)) + ':' +RIGHT(100 +(@t % 60), 2)
``... | Minutes to hh:mm format in SQL Server 2008 query | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
In a document review tool, one can create "batches" of documents. A batch is a group of related documents, identified by GroupID.
These groups of documents are presented to reviewers, who update a field called Testcompleted. This field has 3 possible states: 1, 0 or null. The number of documents in a group varies.
In... | ```
select
b.name,
count(db.DocumentArtifactID) as documents,
-- count only completed
count(case when d.Testcompleted = 1 then d.ArtifactID end) as reviewed,
-- if the minimum = 1 there's no 0 or NULL
case when min(cast(Testcompleted as tinyint)) = 1 then 'yes' else 'no' end as completed
from
... | You can try something like this:
```
select b.name
, count(*) as documents
, sum(d.Testcompleted) as reviewed
, (case when count(*) = sum(d.Testcompleted) then 'yes' else 'no' end) as completed
from [#Document] d
join [#DocumentBatch] db on db.DocumentArtifactID = d.ArtifactID
join [#Batch] b on db.Batc... | How to count if all documents in a group have a value set to 1? | [
"",
"sql",
"sql-server",
""
] |
I have a ORACLE table like this
```
---------------------------------------
DATE | USERID | DOMAIN | VALUE
---------------------------------------
03/16/2016 1001 ASIA 10
03/16/2016 1001 EUROPE 20
03/16/2016 1002 ASIA 20
03/17/2016 1001 ASIA 20
03/17/2016 1... | PIVOT seems to achieve the result you need:
```
SQL> with test (DATE_, USERID, DOMAIN, VALUE)
2 as (
3 select '03/16/2016', 1001 ,'ASIA' ,10 from dual union all
4 select '03/16/2016', 1001 ,'EUROPE' ,20 from dual union all
5 select '03/16/2016', 1002 ,'ASIA' ,20 from... | Do a `GROUP BY`, use `case` expression to chose Asia or Europe:
```
select DATE, USERID,
sum(case when DOMAIN = 'ASIA' then VALUE end) as asia
sum(case when DOMAIN = 'EUROPE' then VALUE end) as europe
from tablename
group by DATE, USERID
```
Answer for products not supporting modern Oracle versions' `PI... | Convert row values into columns based on row values multi level hierarchy | [
"",
"sql",
"oracle",
""
] |
**SAMPLE DATA**
Suppose I have table like this:
```
No Company Vendor Code Date
1 C1 V1 C1 2016-03-08
1 C1 V1 C1 2016-03-07
1 C1 V1 C2 2016-03-06
```
**DESIRED OUPUT**
Desired output should be:
```
No Company Vendor Cod... | If you don't have any identity column for your table then each row is identified by all column values combination it has. That brings us weird `on` statement. It includes all columns we are grouping by and a date column which is max for given tuple `(No_, Company, Vendor)`.
```
select t1.No_, t1.Company, t1.Vendor, t1... | If 1 date only can have 1 record, then you can Query it by search the max date first, then check it.
```
select No_, Company, Vendor, Code, Date
FROM tbl
where Date in
(select MAX(Date) from tbl GROUP BY No_, Company, Vendor)
```
if there is more than 1 row that could have the same date, then you could use `parti... | Custom GROUP BY clause | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have two tables **a** and **b** in my Access Database. In both tables I have the field ID. However in table **a** my ID field is prefixed with '31' where as my ID field in table **b** is not.
So for example
```
table a table b
ID field2 ID field3
31L123 test123 L123 123... | `CONCATENATE()` is not supported in Access SQL. Generally you would use `&` for concatenation.
However I don't think you need concatenate anything for your join's `ON` condition. Just use `Mid()` to ignore the first 2 characters ...
```
ON Mid(a.ID, 3) = b.ID
```
That should work, but performance may become unaccept... | Why don't you just update your query to be something like:
```
SELECT Id, Field2, Field3
FROM a LEFT JOIN b ON RIGHT(a.ID,4) = b.ID
WHERE a.Field2 = 13
```
You could also take the a.ID, and subtract 2 digits from the length of a.ID and then use the RIGHT-most characters in the event of a.ID being longer than 6 chara... | SQL Query that joins two tables on a prefixed and non prefixed field | [
"",
"sql",
"ms-access",
"left-join",
"ms-query",
""
] |
I have an Oracle DB, and I don't control the date format. I want to know what the date format is to ensure that searches like
```
select * from search where search_date>='03/16/2016 00:00:00'
```
work as expected. | Don't do that - you are relying on implicit data type conversion which is going to fail at some point.
You have two options:
1) Use a proper ANSI SQL date literal:
```
select *
from search
where search_date >= timestamp '2016-03-16 00:00:00';
```
2) use `to_date()` (or `to_timestamp()`) and use a custom format.
... | You can get all the `NLS` session parameters with the query:
```
SELECT * FROM NLS_SESSION_PARAMETERS;
```
or, if you have the permissions `GRANT SELECT ON V_$PARAMETER TO YOUR_USERNAME;`, you can use the command:
```
SHOW PARAMETER NLS;
```
If you just want the date format then you can do either:
```
SELECT * FRO... | What is Oracle's Default Date Format? | [
"",
"sql",
"oracle",
"date-formatting",
""
] |
This is the error I get.
> 16.03.2016 12:02:16.413 *WARN* [xxx.xxx.xx.xxx [1458147736268] GET /en/employees-leaders/employee-s-toolkit2/epd-update/epd-update-archives/caterpillar-news/upcoming-brand-webinarfocusonmarketing.html HTTP/1.1] com.day.cq.wcm.core.impl.LanguageManagerImpl Error while
> retrieving language pr... | You don't need a query if you know the Node's UUID, just use the [Session.getNodeByIdentifier(String id)](http://www.day.com/specs/jsr170/javadocs/jcr-2.0/javax/jcr/Session.html#getNodeByIdentifier%28java.lang.String%29) method. | Your query is not SQL as you stated, it's XPATH. Is that a typo or did you run the query incorrectly?
It certainly looks like a UUID. You can query for the `jcr:uuid` property or you can continue doing a full text search.
XPATH:
`/jcr:root//*[jcr:contains(., '91186155-45ad-474-9ad9-d5156a398629')]`
`/jcr:root//*[@j... | How to locate the node in JCR using uuid from query | [
"",
"sql",
"aem",
"jcr",
""
] |
[](https://i.stack.imgur.com/Wexz8.jpg)
[](https://i.stack.imgur.com/eq6eA.jpg)
I need to find the names of aircraft such that **all pilots** certified to operate them earn more than... | You can just look for the opposite case - that **no** pilots earn less than 60,000:
```
SELECT
aname
FROM
Aircraft A
WHERE
NOT EXISTS
(
SELECT *
FROM Certified C
INNER JOIN Employee E ON
E.eid = C.eid AND
E.salary < 60000
WHERE C.aid = A.aid
)... | ```
SELECT aname FROM Aircraft where NOT EXISTS (SELECT eid FROM Employee AS e INNER JOIN Certified AS c ON c.eid=e.eid WHERE salary<60000 AND aid=Aircraft.aid)
``` | How to write this complex SQL query? | [
"",
"mysql",
"sql",
"join",
""
] |
So, I admit it was one of my exam tasks yesterday and I failed to deal with it...
I had simple database of people with their name, salary and function (A, B, C, D, E and F) and I had to select functions that have the biggest and the lowest avg salary. I had also to ignore function C.
Example of database:
```
name ... | Similar to @vkp's approach, but without the join back to the base table:
```
select function, avg_salary
from (
select function, avg(salary) as avg_salary,
rank() over (order by avg(salary)) as rnk_asc,
rank() over (order by avg(salary) desc) as rnk_desc
from tablename
group by function
)
where rnk_asc =... | You could use `rank` function (use `dense_rank` if there can be ties in averages) to order rows by their average salary. Then select the highest and lowest ranked rows.
```
select t1.function, avg(t1.salary)
from (select
rank() over(order by avg(salary) desc) rnk_high
,rank() over(order by avg(salary)) r... | How to select first and last record from ordered query without UNION, INTERSECT etc | [
"",
"sql",
"oracle",
"group-by",
"sql-order-by",
"union",
""
] |
I have many to many association between `contact` and `project`.
```
contact:
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| id ... | I fixed it this way:
```
SELECT numprojects,
Count(*) AS numcontacts
FROM (
SELECT c.id,
Count(pc.contact_id) AS numprojects
FROM contact c
LEFT JOIN project_contact pc
ON pc... | This should work:
```
select
case when project_contracts = 0 then '0 projects'
when project_contracts = 1 then '1 project'
else '2+ projects' end as num_of_projects
count(contracts) as contracts
from
(select
c.id as contracts
sum(case when p.id is null then 0 else 1 end) as projects_contracts
from con... | counting in joins | [
"",
"sql",
"database",
"postgresql",
"join",
"left-join",
""
] |
Let's say that I have simple database like this:
```
People
name age
Max 25
Mike 15
Lea 22
Jenny 75
Juliet 12
Kenny 10
Mark 44
```
and I want to select N the oldest people from there by using JOIN with People table itself. I've tried to JOIN them this way
```
People p1 JOIN People p2 ON p1.age ... | I think what you meant to do is:
```
SELECT t.name,t.age FROM (
SELECT p1.name,p1.age,count(*) as cnt FROM People p1
JOIN People p2ORDER ONBY p1.age < p2.age
GROUP BY p1.name,p1.age) t
WHERE t.cnt <= N
```
But there is not need for that, you can use ORACLE's `rownum`
```
SELECT * FROM (
SELECT * FROM... | Newer Oracle versions support `FETCH FIRST`:
```
select *
from people
order by age desc
fetch first 4 rows only
```
You can also try: `fetch first 4 rows with ties` | Selecting N first rows with the biggest value of an attribute using JOIN with the same table | [
"",
"sql",
"oracle",
"join",
"sql-order-by",
"greatest-n-per-group",
""
] |
<http://sqlfiddle.com/#!4/bab93d>
See the SQL Fiddle example... I have Customers, Tags, and a mapping table. I am trying to implement customer search by tags, and it has to be an AND search. The query is passed a list of tag identifiers (any number), and it has to return only customers that have ALL the tags.
In the ... | You could use correlated subquery to get list of all customers:
```
SELECT *
FROM customer c
WHERE c.customer_ID IN
(
SELECT customer_id
FROM customer_tag ct
WHERE ct.customer_id = c.customer_id
AND ct.tag_id IN (1,2)
GROUP BY customer_id
HAVING COUNT(DISTINCT tag_id) = 2
);
```
`Liv... | `JOIN` version:
```
SELECT c.*
FROM customer c
JOIN (SELECT customer_id
FROM customer_tag
WHERE tag_id IN (1,2)
GROUP BY customer_id
HAVING MAX(tag_id) <> MIN(tag_id)) ct ON c.customer_id = ct.customer_id
```
If you have more than 2 different values, use `COUNT DISTINCT` instead, like this:
... | Oracle return rows only if all join conditions match | [
"",
"sql",
"oracle",
""
] |
I have a table with a foreign key called `team_ID`, a date column called `game_date`, and a single char column called `result`. I need to find when the next volleyball game happens. I have successfully narrowed the game dates down to all the volleyball games that have not happened yet because the result `IS NULL`. I ha... | The `ROWNUM` pseudocolumn is generated before any `ORDER BY` clause is applied to the query. If you just do `WHERE ROWNUM <= X` then you will get `X` rows in whatever order Oracle produces the data from the datafiles and not the `X` minimum rows. To guarantee getting the minimum row you need to use `ORDER BY` first and... | Could you make it simple and order by date and SELECT TOP 1? I think this is the syntax in Oracle:
WHERE ROWNUM <= number; | Find the latest or earliest date | [
"",
"sql",
"oracle",
""
] |
I would like to combine two columns into one and separate by a '/' using SQL statement
Currently, I could only do this.
```
Select A.Marks, Q.NoOfAnsBox FROM AnswerTable AS A INNER JOIN QuestionTable AS
Q WHERE A.QuestionID = Q.QuestionID
```
With the output:
```
Marks NoOfAnsBox
3 5
2 5
```
May I... | In Mysql use the `CONCAT()` function to concatenate strings as `+` acts differently here than in other RDBMS's:
```
Select CONCAT(A.Marks, '/', Q.NoOfAnsBox) As Marks
FROM AnswerTable AS A
INNER JOIN QuestionTable AS Q ON A.QuestionID = Q.QuestionID
```
Also consider changing your "WHERE" to an "ON". In your ca... | ```
Select CONCAT(A.Marks, '/', Q.NoOfAnsBox) AS Marks FROM AnswerTable AS A INNER JOIN QuestionTable AS
Q WHERE A.QuestionID = Q.QuestionID
``` | SQL: How to combine two columns with punctuation? | [
"",
"mysql",
"sql",
"concatenation",
""
] |
I have a table consists of table name, for example:
TableA
```
UID TableName CifKey ...
1 xxx 12345
1 yyy 12345
1 xxx 12345
2 zzz 45678
```
How can I select data from tables that having name same as the `TableName` column in Table A?
For example:
```
S... | Dynamic SQL is the way to go:
```
DECLARE @uid INT = 1,
@cifkey INT = 12345
DECLARE @sql NVARCHAR(MAX) = ''
SELECT @sql = @sql +
'SELECT
A.a, B.b -- Replace with correct column names
FROM TableA A
JOIN ' + QUOTENAME(TableName) + ' B
ON A.Cifkey = B.Cifkey
WHERE
A.uid = @uid
AND A.cifkey =... | You will have to use a dyanmic query - something like this
```
DECLARE @tablename VARCHAR(50)
DECLARE @uid INT = 1
DECLARE @cifkey INT = 12345
SELECT @tablename = TableName FROM TableA WHERE uid = @uid AND cifkey = @cifkey
DECLARE @query VARCHAR(500)
SELECT @query = 'select A.a, B.b from TableA A JOIN ' + @tablename... | How to select data from multiple tables where table name is value from a column of another table? | [
"",
"sql",
"sql-server",
""
] |
table1
```
| email | result |
----------------------------
| abc@gmail.com |0.12 |
| dsv@gmail.com |0.23 |
| rthgmail.com | 0.45 |
| hfg@gmail.com |0.56 |
| yyt@gmail.com | 0.78 |
| hjg@gmail.com | 0.35 |
```
table2
```
| resource |
-------------------
| 0... | You can do it with a sub query:
```
UPDATE Table3 t
SET t.temp = (SELECT s.result+p.resource
FROM table1 s INNER JOIN table2 p
ON(s.email = 'abc@gmail.com'))
```
If your Table3 doesn't have data yet:
```
INSERT INTO Table3
(SELECT s.result+p.resource
FROM table1 s INNER JOIN table2 p
... | Seems like a curious request, but you want an `update` with `join`:
```
UPDATE table3 t3 CROSS JOIN
table2 t2 CROSS JOIN JOIN
(SELECT SUM(t1.result) FROM table1 t1 WHERE t1.email = 'abc@gmail.com') t1
SET t3.temp = t1.result + t2.resource;
```
Are you sure you don't really want an `insert` instead? | Do some calulations of the values in two table and store it in third table mysql | [
"",
"mysql",
"sql",
"database",
"select",
""
] |
I am getting repeating rows when I query this table using the below query. I am not sure why this is happening, could someone please help explain?
I get 4 repeating rows when I query the data when the expected result should be only 1 row.
The query is:
```
SELECT d.DIRECTOR_FNAME, d.Director_lname, s.studio_name
FRO... | First question you should be asking is "What Result Set Am I Looking For?". Your query is returning The Director First Name, Director Last Name, and Studio Name where the Film Title is "The Wolf of Wall Street", for each cast that belongs to that Film. You get 4 records because you get a record for each casting where F... | You are missing a join, instead of an AND , follow this example :
```
SELECT d.DIRECTOR_FNAME, d.Director_lname, s.studio_name
FROM DIRECTOR d
INNER JOIN STUDIO s ON s.STUDIO_ID = f.STUDIO_ID
INNER JOIN CASTING c ON d.DIRECTOR_ID = c.DIRECTOR_ID
INNER JOIN FILM f ON f.FILM_ID = c.FILM_ID
WHERE f.FILM_TITLE = ... | SQL Query prints 4 times/Advice | [
"",
"sql",
"oracle",
"join",
"duplicates",
"inner-join",
""
] |
Let's say I have 20 columns in a table and I run a manual query like:
```
SELECT *
FROM [TABLE]
WHERE [PRODUCT] LIKE '%KRABBY PADDY%'
```
After viewing the results, I realize I only need 10 of those columns. Is there a quick way to list out the 10 columns you want, something like right clicking on the wild ca... | Right clicking the `*` and selecting the columns doesn't sound terribly fast either.
You can use SSMS to go to the table, and drag the "Columns":
[](https://i.stack.imgur.com/rFmr3.png)
You'll get every column, and then you can keep the ones you want... | As far as I know you can't do exactly what you are asking for, but in SQL Server Management Studio you can obtain the SELECT statement with all the columns of a table by right-clicking he table on the object explorer an select the options:
> **script table as** --> **SELECT to** --> **Clipboard**
Once you have this S... | Quickly going from * wild card to a few specific columns | [
"",
"sql",
"sql-server",
"ssms",
""
] |
If I have the below select query:
```
select col1, col2, col3, sum(value1) as col4, col5
from table1
group by col1, col2, col3, col5
```
How to add col6 = col4/col5? | You cannot access the alias in the `SELECT` clause. So you have to repeat `sum(value1)`:
```
select col1, col2, col3,
sum(value1) as col4,
col5,
sum(value1) / col5 as col6
from table1
group by col1, col2, col3, col5
``` | Do the `GROUP BY` in a derived table:
```
select col1, col2, col3, col4, col5, col4/col5 as col6
from
(
select col1, col2, col3, sum(value1) as col4, col5
from table1
group by col1, col2, col3, col5
) dt
``` | Divide two columns into group by function SQL | [
"",
"sql",
"sql-server",
"group-by",
"divide",
""
] |
IΒ΄m having a problem with a query.
```
select p.id, p.firstname, p.lastname , max(s.year) as 'Last Year', min(s.year) as 'First Year', c.name from pilot p
join country on country.sigla = p.country
join circuit c on c.country_id = country.sigla
join season s
on(p.id = s.pilot_id)
group by p.id, p.firstname, p.lastname... | Borrowed answer from above with further explanation because I couldn't comment on it.
You'll need to write subqueries for the first year and the last year to use different select criteria for each. For the first year, you want to order by the year ASC to get the smallest year in the column. For last year, you'll want t... | I suspect the issue is with the join to the `circuit` table.
There's no need to replace the `MIN(s.year)` and `MAX(s.year)` expressions in the select list. (Despite what other answers recommend, that does nothing to address the real issue... getting a result that meets the specification to return only *one* row per pi... | SQL - Query between four tables | [
"",
"sql",
"sql-server",
"database",
"relational-database",
""
] |
I have the following values in my database:
[](https://i.stack.imgur.com/aptOa.png)
I would like to create a unique key on `tv_series_id+name+tv_season_number+tv_episode_number`. However, the above does not work for my purposes using the conventional... | As requested, my suggestion (untested):
```
ALTER TABLE main_itemmaster ADD COLUMN uniquer BIGINT NOT NULL;
DELIMITER $$
CREATE TRIGGER add_uniquer BEFORE INSERT ON main_itemmaster
FOR EACH ROW
BEGIN
SET NEW.uniquer = (SELECT UUID_SHORT());
END $$
DELIMITER ;
ALTER TABLE main_itemmaster ADD UNIQUE KEY (tv_seri... | More simple solution (if you have a lot of fields, which could be NULL and if you still want to have rows unique)
1) add unique\_hash field
```
ALTER TABLE `TABLE_NAME_HERE`
ADD `unique_hash` BIGINT unsigned NOT NULL DEFAULT '0' COMMENT 'JIRA-ISSUE-ID' AFTER `SOME_EXISTING_FIELD`
;
```
2) fill them
```
UPDAT... | Preferred way to create composite unique index with NULL values | [
"",
"mysql",
"sql",
"indexing",
""
] |
All, I have a table with similar values to this:
```
Name Value Server time
a None 3/17/2016 11:59:50 PM
a None 3/17/2016 11:59:36 PM
a None 3/17/2016 11:59:33 PM
a March Madness 3/17/2016 11:59:33 PM
a None 3/17/2016 11:59:19 PM
b TGIF 3/17/2016 11:59:04 PM
b None 3/17/2016 11:5... | If you don't care about "c", an easy way uses a `where` clause:
```
select t.*
from t
where t.servertime = (select max(t2.server_time)
from t t2
where t2.name = t.name and t2.value <> 'None'
);
```
If you do want all names, then you can use an aggregati... | **[SQL Fiddle Demo](http://sqlfiddle.com/#!15/4ebfd5/30)**
Using just SQL you need create a list of every Name using distinct. Then join to find the MAX(sever time) for each name. Then a third join to get the value. Finally the NULL become `0` like the case for `c`
```
SELECT S."Name",
T.mtime,
CASE W... | Get Last Value that is not 'None' | [
"",
"sql",
"t-sql",
""
] |
I have a view cnst\_prsn\_nm . I want to check for records which share same cnst\_mstr\_id and same last name but differ on first names. So I did in Teradata SQL
```
SELECT TOP 20 prsn_nm_a.cnst_mstr_id FROM arc_mdm_vws.bz_cnst_prsn_nm prsn_nm_a
INNER JOIN arc_mdm_vws.bz_cnst_prsn_nm prsn_nm_b
ON prsn_nm_a.cnst_... | Your original query is not correct (`WHERE` goes before `GROUP BY`) Let me assuming you mean this:
```
SELECT TOP 20 prsn_nm_a.cnst_mstr_id
FROM arc_mdm_vws.bz_cnst_prsn_nm prsn_nm_a INNER JOIN
arc_mdm_vws.bz_cnst_prsn_nm prsn_nm_b
ON prsn_nm_a.cnst_mstr_id = prsn_nm_b.cnst_mstr_id
WHERE prsn_nm_a.bz_cnst_p... | The clauses in a SQL statement always come in a specific order. First `SELECT`, then `FROM`, then `JOIN`s, then `WHERE`, then `GROUP BY`, then `HAVING`. You cannot deviate from that order, and do not need (and cannot have) a second `WHERE` clause. Make your one and only `WHERE` clause include ***all*** the condition yo... | LEFT JOIN after Group By and HAVING | [
"",
"sql",
"group-by",
"teradata",
""
] |
A conundrum I can't figure out
Giving these data in an Oracle table (named tbs\_test). First row are column names
```
A |B| C
100|6|1000
100|6|1001
100|6|1002
100|7|1003 **
200|6|2000
200|6|2001
300|7|3000
300|7|3001
400|6|4000 **
400|7|4001
400|7|4002
```
Through an Oracle SQL select I want to retrieve the two rec... | You can do this with aggregation and analytic functions:
```
select a, b, c
from (select a, b, max(c) as c,
row_number() over (partition by a order by count(*)) as seqnum,
count(*) over (partition by a) as numBs
from tbs_test t
group by a, b
) ab
where seqnum = 1 and numBs >... | **Oracle Setup**:
```
CREATE TABLE tbs_test (A, B, C )AS
SELECT 100,6,1000 FROM DUAL UNION ALL
SELECT 100,6,1001 FROM DUAL UNION ALL
SELECT 100,6,1002 FROM DUAL UNION ALL
SELECT 100,7,1003 FROM DUAL UNION ALL
SELECT 200,6,2000 FROM DUAL UNION ALL
SELECT 200,6,2001 FROM DUAL UNION ALL
SELECT 300,7,3000 FROM DUAL UNION ... | An extreme multidimension Oracle Group By Select | [
"",
"sql",
"oracle",
"group-by",
""
] |
OK so here's what I'm trying to accomplish.
Table 1 has a column called inifile, path. Entries look like...
```
----------------------------------
| inifile | path |
----------------------------------
|example1.ini | c:\temp\text.txt |
|example2.ini | c:\temp\text2.txt |
---------------------------... | Try this:
```
SELECT Table2.jobs, table2.JobName, table1.Path
FROM
Table1
JOIN Table2 ON table2.jobs = REPLACE(table1.inifile, '.ini','')
``` | If you are guaranteed that there is at most one occurrence of '.ini' within the string value, and that it's at the end of the string, then the `REPLACE` function (demonstrated in other answers) can work for you.
To trim the string at the first occurrence of '.ini', you could use the `SUBSTRING_INDEX` function
```
SE... | Need a SQL Query to string trim from data in 1 table and match to another | [
"",
"sql",
""
] |
I have 4 tables:
```
CREATE TABLE ROLE (
id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE PROFILE (
id INT PRIMARY KEY,
batch VARCHAR(10)
);
CREATE TABLE USER (
id INT PRIMARY KEY,
name VARCHAR(50),
role_id INT REFERENCES ROLE(id),
profile_id INT REFERENCES PROFILE(id)... | [SQL Fiddle](http://sqlfiddle.com/#!9/35893b/7)
**MySQL 5.6 Schema Setup**:
```
CREATE TABLE ROLE (
id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE PROFILE (
id INT PRIMARY KEY,
batch VARCHAR(10)
);
CREATE TABLE USER (
id INT PRIMARY KEY,
name VARCHAR(50),
role_id INT R... | Could be this query
```
select user.name, count(post.id)
from user
inner join role on user.role_id = role.id
inner join profile on user.profile_id = profile.id
inner join post on user.id = post.user_id
where profile.batch = '2008'
and role.name = 'alumni'
group by user.name
order by user.name ;
```
If you want onl... | query to display the name(s) of the alumni user (Role-βAlumniβ) from 2008 batch who has/have posted the maximum number of posts, sorted by name | [
"",
"mysql",
"sql",
""
] |
I have rows in my table that needs deleting based on a few columns being duplicates.
e.g Col1,Col2,Col3,Col4
If Col1,Col2 and Col3 are duplicates regardless of what value is in Col4 I want both these duplicates deleted. How do I do this? | You can do this using the `where` clause:
```
delete from t
where (col1, col2, col3) in (select col1, col2, col3
from t
group by col1, col2, col3
having count(*) > 1
);
``` | Group by these IDs and check with HAVING whether there are duplicates. With the duplicates thus found delete the records.
```
delete from mytable
where (col1,col2,col3) in
(
select col1,col2,col3
from mytable
group by col1,col2,col3
having count(*) > 1
);
``` | Deleting Semi Duplicate Rows in ORACLE SQL | [
"",
"sql",
"oracle",
""
] |
I have 2 tables that can have many-to-many relations between them:
```
Person (pid, name, a,b) ,
Attributes (attribId, d,e)
```
The mapping is present in a separate table:
```
Mapping (mapId, pid, attribId)
```
The goal is to get all Person and Attributes values for a person who qualifies the filter criteria. The ... | You can get all persons satisfying the filter using:
```
select m.pid
from mapping m join
attributes a
on m.attribId = a.attribId and a.d = 'dS';
```
You can get all person/attribute combinations using `IN` or `EXISTS` or a `JOIN`. Which is better depends on the database. But the idea is:
```
select p.*, a... | First thing I have noticed is that you use left join in subqueries, inner join would work as well and is much faster. Second remove Person from nested selects because it is not needed.
```
select m2.pid
from
Mapping m2
inner join
Attributes a2
on m2.attribId=a2.attribId
where
a2.d = 'd5'
``` | Optimizing sub-queries and joins | [
"",
"sql",
"sql-optimization",
""
] |
I have a database which (For whatever reason) has a column containing pipe delimited data.
I want to parse this data quickly, so I've thought of converting this column (nvarchar) into an XML by replacing the pipes with XML attributes and putting it into an XML data typed column somewhere else.
It works, except in the... | ```
SELECT CAST('<values><f>' +
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(value,'&','&')
,'"','"')
,'<','<')
,'>','>')
,'|','</f><f>') + '</f></values>' AS XML)
FROM TABLE;
``` | Your idea was absolutely OK: By making an XML out of your string the XML engine will convert all special characters properly. After your splitting the XML should be correct.
If your string is stored in a column you can avoid the automatically given name by either doing kind of *computation* (something like `'' + YourC... | How to encode XML in T SQL without the additional XML overhead | [
"",
"sql",
"sql-server",
"xml",
"t-sql",
""
] |
I have a scenario in which I have to get those users whose age is between say (10 - 20) in sql, I have a column with date of birth `dob`. By executing the below query I get the age of all users.
```
SELECT
FLOOR((CAST (GetDate() AS INTEGER) - CAST(dob AS INTEGER)) / 365.25) AS Age
FROM users
```
My question... | I don't have a SQL-Server available to test right now. I'd try something like:
```
select * from users where datediff(year, dob, getdate()) between 10 and 20;
``` | First add computed field `Age` like you already did. Then make where filtering on the data.
```
SELECT * FROM
(SELECT FLOOR((CAST (GetDate() AS INTEGER) - CAST(dob AS INTEGER)) / 365.25) AS Age, *
from users) as users
WHERE Age >= 10 AND Age < 20
```
There are [number of ways](https://stackoverflow.com/questio... | Get between ages from date of birth in sql | [
"",
"sql",
""
] |
I have a TraitQuestion model that have a number of traits or answers - each of which has a value such as 1, 2, 3, or -3105 (for none of the above). I can't change these values because they are required for an external API.
I'd like to order them by the value, but when I do that, the answer with -3105 shows up at the t... | I don't know if this will work for you or not but try this:
```
@trait_question.traits.order('ABS(value)')
```
The `ABS` will change the negative value to positive hence taking the absolute value each time. If your database field is `string` then you can do it like this as suggested by Tom which worked for him:
```
... | Hey you can try this way
```
@trait_question.traits.order("CASE WHEN (value AS integer > 0) THEN value ELSE (value As integer)*(-1) END")
```
Other wise use
```
@trait_question.traits.order("abs(value AS integer)")
``` | Rails Order by SQL | [
"",
"sql",
"ruby-on-rails",
""
] |
I have a simple table as scripted below.
```
CREATE TABLE dbo.KeyNumbers (
RowId INT IDENTITY
,ProFormaNumber NCHAR(10) NULL
,SalesOrderNumber NCHAR(10) NULL
,PurchaseOrderNumber NCHAR(10) NULL
,InvoiceCreditNoteNumber NCHAR(10) NULL
,InvoiceNumber NCHAR(10) NULL
,PurchaseInvoiceCreditNoteNumber NCHAR(10) ... | The obvious method uses a trigger on insert to be sure the table is empty.
I've never tried this, but an index on a computed column might also work:
```
alter table dbo.KeyNumbers add OneAndOnly as ('OneAndOnly');
alter table dbo.KeyNumbers add constraint unq_OneAndOnly unique (OneAndOnly);
```
This should generate... | --I think this would be cleaner and utilizes the existing columns
```
CREATE TABLE dbo.KeyNumbers (
RowId AS (1) PERSISTED
,ProFormaNumber NCHAR(10) NULL
,SalesOrderNumber NCHAR(10) NULL
,PurchaseOrderNumber NCHAR(10) NULL
,InvoiceCreditNoteNumber NCHAR(10) NULL
,InvoiceNumber NCHAR(10) NULL
,PurchaseInvoiceCr... | Is it possible to restrict a sql table to only have a single row at the design stage | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
Most resources that describe a `SELECT TOP ...` query in Postgres say that you should use `LIMIT` instead, possibly with an `ORDER BY` clause if you need to select the top elements by some ordering.
What do you do if you need to select the top N elements from a recursive query, where there is no ordering and there is ... | Your assessment is to the point. The recursive query in [my referenced answer](https://stackoverflow.com/questions/8674718/best-way-to-select-random-rows-postgresql/8675160#8675160) is only somewhat more flexible than the original simple query. It still requires relatively few gaps in the ID space and a sample size tha... | This is too long for a comment, but is informative about what's going on with my existing query. From the [documentation on recursive query evaluation](http://www.postgresql.org/docs/9.5/static/queries-with.html), the steps that a recursive query will take are:
> Evaluate the non-recursive term. For UNION (but not UNI... | How to guarantee that at least N rows are returned by recursive CTE in Postgres | [
"",
"sql",
"postgresql",
"common-table-expression",
"recursive-query",
"sql-limit",
""
] |
What is the difference between the following 2 queries?
```
DELETE FROM experience WHERE end IS NOT NULL;
```
And
```
DELETE FROM experience WHERE NOT( end=NULL);
```
First query was accepted as a correct answer but second was not. | NULL values are treated differently from other values.
NULL is used as a placeholder for unknown or inapplicable values.
It is not possible to test for NULL values with comparison operators, such as =, <, or <>
You will have to use the IS NULL and IS NOT NULL operators instead.
Please refer below link for more detai... | NULLs are a bit weird. A NULL is *never* equal to *anything **including another NULL.*** Further, any boolean operation against a NULL returns NULL.
The expression `end IS NOT NULL` will evaluate **`false`** if `end` is NULL, and **`true`** if `end` is not NULL.
The expression `NOT( end=NULL)` will actually always ev... | Difference between "IS NOT NULL" and "NOT (field = NULL)" in these 2 queries | [
"",
"mysql",
"sql",
""
] |
I have script where I want to first drop view and then create it.
I know how to drop table:
```
IF EXISTS (SELECT * FROM sys.tables WHERE name = 'table1' AND type = 'U') DROP TABLE table1;
```
so I did the same for views:
```
IF EXISTS (SELECT * FROM sys.views WHERE name = 'view1' AND type = 'U') DROP VIEW view1;
cr... | your exists syntax is wrong and you should seperate DDL with go like below
```
if exists(select 1 from sys.views where name='tst' and type='v')
drop view tst;
go
create view tst
as
select * from test
```
you also can check existence test, with object\_id like below
```
if object_id('tst','v') is not null
drop view ... | ```
DROP VIEW if exists {ViewName}
Go
CREATE View {ViewName} AS
SELECT * from {TableName}
Go
``` | Drop view if exists | [
"",
"sql",
"sql-server",
"view",
"create-view",
""
] |
Actually, I have 2 tables the friend table and the users table
what I try to achieve is to retrieve my mutual friend by checking the friend of another user and get the data of these mutual friends from the user's table
table friend is built like this
```
id | user1 | user2 | friend_status
```
then the table data loo... | You can use a `UNION` to get a users friends:
```
SELECT User2 UserId FROM friends WHERE User1 = 1
UNION
SELECT User1 UserId FROM friends WHERE User2 = 1
```
Then, joining two of these `UNION` for two different Users on `UserId` you can get the common friends:
```
SELECT UserAFriends.UserId FROM
(
SELECT User2 ... | Here's a way using `union all` to combine all friends of user 1 and user 2 and using `count(distinct src) > 1` to only select those that are friends with both users.
```
select friend from (
select 2 src, user1 friend from friends where user2 = 2
union all select 2, user2 from friends where user1 = 2
union... | Finding mutual friend sql | [
"",
"sql",
"mutual-friendship",
""
] |
I am writing an query to select player bans from another table but firstly its very slow taking around 7-14 seconds and secondly its returning invalid rows.
The first query is as follows:
```
SELECT *
FROM sourcebans.sb_bans
WHERE removetype IS NULL
AND removedon IS NULL
AND reason NOT LIKE '%[Frag... | The query returns rows that are not `NULL` because it is interpreted as
`(... AND ... AND ... ) OR ...` instead of
`... AND ... AND ( ... OR ...)`
So you need to add a braces, also the `DISTINCT` is not needed:
```
SELECT *
FROM sourcebans.sb_bans
WHERE removetype IS NULL
AND removedon IS NULL
... | the and have higher priority then or...
You need have to index on your tables
np. add index to trackingid field in fragsleuth.history if you don't have
You can probably do faster using one sub query, but i'm not sure this.
```
SELECT *
FROM sourcebans.sb_bans
WHERE removetype IS NULL
AND removedon IS NULL
AND re... | MySQL Query returning invalid rows and very slow | [
"",
"mysql",
"sql",
"performance",
""
] |
I honestly have no idea how to give a better title for this :(
Basically I have these 3 tables
```
Table "public.users"
Column | Type | Modifiers
--------+-----------------------+----------------------------------------------------
id | integer | not null default... | You have the right idea. Just continue with it:
```
SELECT u.id as userId, c.id as commentId, u.name, c.content, c.rn
FROM users u LEFT JOIN
(SELECT c.*,
ROW_NUMBER() OVER (PARTITION BY c.user_id) as rn
FROM comments c
) c
ON u.id = c.user_id LEFT JOIN
(SELECT v.*,
ROW_... | Because users to comments and comments to votes both have 1-to-many relationships, doing both joins will give you CxV (3x2=6) rows per user.
Because comments will be duplicated when a comment has more than 1 vote, use `dense_rank()` instead of `row_number()` so that "duplicate" comments will have the same rank and be ... | LIMIT the results of nested JOIN queries | [
"",
"sql",
"postgresql",
""
] |
I am formatting a number which is Date and I want to display only day and month part **(e.g. Jan 1, Jan 2, Jan 3, Jan 4β¦)** of this but it is not formatting and displaying the complete date.
**Whereas If I use the same wizard with tabular then it is working fine.**
I am using wizard to format data
[](https://i.stack.imgur.com/2cdwh.gif) | In the altanative, you could use datename function in sql server for that Column
SELECT DATENAME(DAY,Col\_Name)+', '+LEFT(DATENAME(MONTH,Col\_Name),3)
that is
SELECT DATENAME(DAY,'2016-03-21')+', '+LEFT(DATENAME(MONTH,'2016-03-21'),3) | How to format a number in SSRS Report for Matrix? | [
"",
"sql",
"sql-server",
"reporting-services",
"ssrs-2008",
"ssrs-2008-r2",
""
] |
I'm looking for a way group `empNumber` together and can't seem to find a way
This is my current query:
```
SELECT EmpNumber, [Match], [NonMatch], [Base], [SRA], [SRS]
from
(select a.empnumber, TT_GB.MAXDate, a.TT_Plan, a.TT_Ratio
from table_1 as a
inner join
(select b.empnumber, b.TT_Plan, MAX(b.TT_Date) as M... | I don't think this is the best solution but you can do it by creating an alias table like the following:
```
Select t.EmpNumber, Sum(t.Match), Sum(t.NonMatch), Sum(t.Base), Sum(t.SRA), Sum(t.SRS) from
(
SELECT EmpNumber, [Match], [NonMatch], [Base], [SRA], [SRS]
from
(select a.empnumber, TT_GB.MAXDate, a.TT_Plan,... | So how I wrote before
```
declare @table_1 table ( EmpNumber int, TT_Plan varchar(20), TT_Date date, TT_Ratio int )
insert @table_1
values
(1,'Base','2008-05-11',11)
,(1,'Base','2015-08-22',12)
,(1,'Base','2010-07-09',13)
,(1,'Match','2003-01-23',15)
,(1,'Match','2000-11-17',14)
,(1,'NonMatch','2014-09-22',19... | GROUP BY after you get the result from PIVOT | [
"",
"sql",
"sql-server",
""
] |
I've been using this for *years*, so it is high time to understand it fully. Suppose a query like this:
```
SELECT
*
FROM a
LEFT JOIN b ON foo...
LEFT JOIN c ON bar...
```
The [documentation](http://www.postgresql.org/docs/current/static/queries-table-expressions.html) tells us that
> `T1 { [INNER] | { LEFT | RIG... | A `FROM` clause parses the conditions from left to right (unless overridden by parentheses). So:
```
FROM a
LEFT JOIN b
ON foo...
LEFT JOIN c
ON bar...
```
is parsed as:
```
FROM (
a
LEFT JOIN b
ON foo...
)
LEFT JOIN c
ON bar...
```
This is explained in the [docume... | Here is multiple join operation.
SQL is a language where you describe the results to get, not how to get them. The optimizer will decide which join to do first, depending on what it thinks will be most efficient.
You can read here some information
<https://community.oracle.com/thread/2428634?tstart=0>
I think, it... | Multiple LEFT JOINs - what is the "left" table? | [
"",
"sql",
"postgresql",
"join",
"outer-join",
""
] |
I need a query to find a film featuring both **Keira Knightly** and **Carey Mulligan**.
How would I go about finding these two various actors that have played a role in the same movie. I have attempted it myself and it has resulted in repeating rows. I think because I wasn't using inner joins possibly. Could someone p... | Your query actually return correct results? I doubt it..
You can use EXISTS() :
```
SELECT f.film_title AS "Mulligan and Knightly"
FROM Film f
INNER JOIN film_actor x
ON(f.film_id = x.film_id)
INNER JOIN actor a
ON(x.actor_id = a.actor_id)
WHERE a.actor_id = 8
AND EXISTS(select 1 FROM film_actor s
... | Perhaps something like this will do it?
```
select f.filmTitle as 'mulligan and knightly' from film f inner join film_actor fa on f.film_id = fa.film_id inner join actor a on fa.actor_id = a.actor_id where a.actor_lname = 'Knightley'
intersect
select f.filmTitle as 'mulligan and knightly' from film f inner... | Query for multiple conditions | [
"",
"sql",
"oracle",
"inner-join",
""
] |
is it possible to us a CTE to perform multiple update commands?
```
With Query AS
(
SELECT
Table_One.FOO AS FOO,
Table_Two.BAR AS BAR
FROM FOO
JOIN BAR ON FOO.ID = BAR.ID
)
UPDATE
Query.FOO = 1;
UPDATE
Query.BAR = 2;
```
In the example Query isn't available anymore on the second UP... | A SQL Server `UPDATE` only allows you to update a single table. As buried in the [documentation](https://msdn.microsoft.com/en-us/library/ms177523.aspx):
> The following example updates rows in a table by specifying a view as
> the target object. The view definition references multiple tables,
> however, the `UPDATE` ... | You can insert your `CTE` result to a `@Table` variable and use this Table wherever required in the code block. (You can `join` this Table with actual table to perform the `UPDATE/INSERT/DELETE` etc). You can't use the same CTE in multiple statement, because CTE is part of the subsequent statement only. | USING Common Table Expression and perform multiple update commands | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a dataset in Excel where I have a few thousand id's. In a database I need a few columns to match these ids but some ids are listed twice in the Excel list (and they need to be there twice). I'm trying to write a query with an IN statement, but it automatically filters the duplicates. But I want the duplicates as... | You need to use a `left join` if you want to keep the duplicates. If the ordering is important, then you should include that information as well.
Here is one method:
```
select t.*
from (values (1, id1), (2, id2), . . .
) ids(ordering, id) left join
table t
on t.id = ids.id
order by ids.ordering;
```
... | If I understand this correctly this is exactly the way `IN` is supposed to work...
```
DECLARE @tbl TABLE(value INT, content VARCHAR(100));
WITH RunningNummber AS
(
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS Nmbr
FROM sys.objects
)
INSERT INTO @tbl
SELECT Nmbr,'Content for ' + CAST(Nmbr AS VARCHAR(100... | T-SQL: select * from table where column in (...) with duplicates without using union all | [
"",
"sql",
"sql-server",
"t-sql",
"duplicates",
""
] |
I'm trying to select a column from another table like I used to do in **MSSQL**:
```
select * , Date = (select top 1 Date from [dbo].TableB where status = 1 order by Date desc)
from [dbo].TableA
```
**How can I do that in PostgreSQL?**
Additional sample data:
> TableA
```
Names
Richards
Marcos
Luke
Matthew
John... | `Date = (...)` is invalid (standard) SQL and won't work in Postgres (or any other DBMS except for SQL Server)
A column alias is defined using `AS ...` in SQL (and Postgres). Postgres also doesn't have `top`. It uses `limit`.
Using square brackets in an identifier is also not allowed in SQL. So `[dbo]` needs to become... | I'm not sure if this is the correct syntax, but did you try this:
```
select * , (select NewColumn from [dbo].TableB) as NewColumn
from [dbo].TableA
```
I hope it helps. | PostgreSQL: How to add Column from other table in select statement? | [
"",
"sql",
"postgresql",
""
] |
I'm continue discovering `SQL` and store procedure, having trouble that `@feedid` is returning only 1 id, but it have for ex. 20. How to return array of id's?
```
CREATE PROC spGetItemsByUser
@userName NVARCHAR(50)
AS BEGIN
DECLARE @userId INT,
@feedId INT;
SELECT @userId = ID
FROM users
... | You have to use *table* variables:
```
declare @userId table (uid int)
declare @feedId table (id int)
insert into @userid(uid)
select id
from Users
where name = @userName
insert into @feedid(id)
select feedid
from userstofeed
where userid in (select uid from @userId)
select * from feed where id in (select id fr... | Or just go by simple and plain join
```
create proc spGetItemsByUser
@userName nvarchar(50)
as
begin
select * from Users usr
join UsersToFeed utf on usr.id = utf.userID
join feed fee on utf.feedid = fee.id
where usr.name = @userName
end
``` | Return all id's from table in store procedure | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I am using an Oracle SQL Db and I am trying to count the number of terms starting with X letter in a dictionnary.
Here is my query :
```
SELECT Substr(Lower(Dict.Term),0,1) AS Initialchar,
Count(Lower(Dict.Term))
FROM Dict
GROUP BY Substr(Lower(Dict.Term),0,1)
ORDER BY Substr(Lower(Dict.Term),0,1);
```
This q... | You can use a subquery. Because Oracle follows the SQL standard, `substr()` starts counting at 1. Although Oracle does explicitly allow 0 (["If position is 0, then it is treated as 1"](https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions162.htm)), I find it misleading because "0" and "1" refer to the same p... | I prefer [subquery factoring](http://docs.oracle.com/cd/E11882_01/timesten.112/e21642/state.htm#TTSQL503) for this purpose.
```
with init as (
select substr(lower(d.term), 1, 1) as Initialchar
from dict d)
select Initialchar, count(*)
from init
group by Initialchar
order by Initialchar;
```
Contrary to opposite me... | Using part of the select clause without rewriting it | [
"",
"sql",
"oracle11g",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.