Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm storing hierarchical data in a table. When a resource is accessed by its hierarchical path (grantParent/parent/resource), I need to locate the resource using a CONNECT BY query.
Note: SQL commands are exported from EnterpriseDB, but it should work in Oracle too.
Table structure:
```
CREATE TABLE resource_hierarc... | *Disclaimer: My primary experience belongs to Oracle DBMS, so pay attention to details if applying solution to Postgres.*
---
`Where` clause applied after full hierarchy already built, therefore in original query database engine started retrieving data with specified `resource_name` at any level and building a full t... | ```
select
LEVEL,
resource_id,
resource_type,
resource_name,
parent_id
from
resource_hierarchy
connect by prior parent_id = resource_id
start with UPPER(resource_name)= UPPER(:resource_name);
```
Using this approach, you would not have to use the CASE statements. Just mentionin... | Connect by query | [
"",
"sql",
"oracle",
"connect-by",
"hierarchical-query",
"enterprisedb",
""
] |
Good afternoon,
I'm having an issue with two tables that I'm trying to join.
What I am trying to do is, I have to print a table with all products that is registered in some agenda (codControl), so the person can put his price.
But first I have to look into **lctocotacao** to see if he had already given a price to so... | You need a `LEFT JOIN`, but you also need to be careful about the filtering conditions:
```
SELECT cadc.cod, cadc.desc, lcto.codEnt, lcto.price
FROM cadprodutoscotacao cadc LEFT JOIN
lctocotacao lcto
ON cadc.codControl = lcto.codControl AND
cadc.cod = lcto.cod AND
lcto.codEnt = '19'
WHERE cad... | Your rows are filtered because you specified `JOIN`, which is a shortcut for `INNER JOIN`
If you want all the records from the left table, even if they don't have correlated records in the right table, you should do a `LEFT JOIN`:
```
SELECT cadc.cod, cadc.desc, lcto.codEnt, lcto.price
FROM cadprodutoscotacao cadc
L... | SQL join two tables and the elements that satisfies one condition | [
"",
"sql",
"postgresql",
"join",
""
] |
How can you query on just the time portion of an Orace date field. Ie:
```
select * from mytable
where
date_column < '05:30:00'
```
Want the query to return any rows where the time represented by date\_column is less than 5:30 regardless of the date. | You can try like this:
```
select * from mytable
where
to_char( date_column, 'HH24:MI:SS' ) < '05:30:00'
``` | You can see how far the date is from midnight, and filter on that:
```
select * from mytable
where date_column - trunc(date_column) < 5.5/24
```
The `date_column - trunc(date_column)` calculation will give you a fraction of a day, as is normal for [date arithmetic](http://docs.oracle.com/cd/E11882_01/server.112/e410... | Oracle query on time (and not date) | [
"",
"sql",
"oracle",
"date",
"datetime",
""
] |
I have a database that contains IDs and their associated coordinates.
If I have two ID's what is the most efficient TSQL query that returns the linear distance between these two point?
I know how to do it by using 4 variables and 3 select statements but is there a better way?
```
ID | X | Y
1 | 10 | 15
2 | ... | I'm not sure what you mean by "linear distance", but here is one way to get the Manhattan distance:
```
select abs(p1.x - p2.x) + (abs(p1.y - p2.y)
from points p1 cross join
points p2
where p1.id = 1 and p2.id = 2;
```
Euclidean distance would use appropriate functions. | Building on GL's code for Euclidean distance:
```
DECLARE @points TABLE (ID INT IDENTITY, X DECIMAL(8,4), Y DECIMAL(8,4))
INSERT INTO @points (X,Y) VALUES (10,15),(12,20)
SELECT * FROM @points
SELECT ROUND(SQRT((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y)),2)
FROM @points p1 CROSS JOIN
@points p2
WHERE p1.id... | SQL Calculate XY distance between two XY Coordinates with one query | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I usually search column names in Oracle as we have 1000+ tables. Is there simpler way to search column names using regex.
For example Column name have CURRENCY or COUNTRY etc. | I think it duplicate.
But can find it using below query.
```
SELECT column_name, table_name FROM user_tab_columns WHERE column_name like '%CURRENCY%' OR column_name Like '%COUNTRY%';
``` | I would use the answer of [this SO question](https://stackoverflow.com/a/8739400/3227403) and dump all data to a text file.
At that point I'd use any good text editor with regex search to search the text file and have an immediate overview of what is what.
This works very well as long as tables and columns do not cha... | How to check all column names of Tables in oracle with regex? | [
"",
"sql",
"oracle",
""
] |
I have postgresql table that looks like this:
```
+----+---------------------+
| id | names |
+----+---------------------+
| 1 | foo|bar and biz|pop |
+----+---------------------+
```
I want to select row containing given name. Something like
```
SELECT "id" FROM "table" WHERE "names" LIKE '%foo%';
i... | First, storing multiple values in a single column is a bad idea:
* SQL is not very good at string operations.
* Such operations cannot make use of indexes.
* You cannot use foreign key relationships to validate values.
Instead, you should be using a junction table. Postgres also has other solutions for storing lists,... | While stuck with your unfortunate design, convert to an array and use the `ANY` construct:
```
SELECT id
FROM table
WHERE 'bar' = ANY (string_to_array(names, '|'));
```
About `ANY`, `@>`, arrays and indexes:
* [Can PostgreSQL index array columns?](https://stackoverflow.com/questions/4058731/can-postgresql-index-a... | Is there a way to select like with custom separator | [
"",
"sql",
"postgresql",
"sql-like",
""
] |
The below query that should return a row for every Reading\_Type, plus either the saved Reading value for that Reading\_Type and date, or 0 if no Reading has been saved.
```
SELECT
t.*
, ISNULL(r.Reading, 0) AS Reading
FROM
Reading_Type t
LEFT JOIN
Reading r ON t.Reading_Type_ID = r.Reading_Type_ID
W... | Your WHERE criteria is causing your filter problem (done this myself only a million times or so). Try this instead:
```
SELECT
t.*
, ISNULL(r.Reading, 0) AS Reading
FROM
Reading_Type t
LEFT JOIN
Reading r ON t.Reading_Type_ID = r.Reading_Type_ID
AND r.Reading_Date = @date
```
Leave out the WHERE cla... | if r.Reading\_Date can be null and you want to include those then
```
SELECT t.*, ISNULL(r.Reading, 0) AS Reading
FROM Reading_Type t
LEFT JOIN Reading r
ON r.Reading_Type_ID = t.Reading_Type_ID
AND isnull(r.Reading_Date, @date) = @date
``` | SQL JOIN - return a row for each Table A, regardless if Table B has values or not | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
[](https://i.stack.imgur.com/XituG.png)
I have a table of user with differents fields : id, firstname, name.
I have a table called friend with differents fields : invite\_id, friend\_sender (id of a user), friend\_receiver (id of a user), validity (bo... | Try this:
```
SELECT u.*
FROM user u
WHERE u.id IN (
SELECT f.friend_sender
FROM friend f
WHERE f.friend_receiver = 2 -- My fixed ID about Jin Jey
UNION
SELECT f.friend_receiver
FROM friend f
WHERE f.friend_sender = 2 AND f.validity = 1)
```
I used UNION because you can query two sets of ... | I know there are already answers, but mine is unique AND I have a fiddle! ;)
```
SELECT
id,
firstname,
name
FROM
user
WHERE id IN
(
SELECT
CASE WHEN friend_sender = 1 THEN friend_receiver ELSE friend_sender END
FROM friend
WHERE
(friend_sender = 1 OR friend_receiver = 1)
AND
validity = 1
)
```
**Fiddle:... | Finding friends of a user | [
"",
"mysql",
"sql",
""
] |
Sorry for the strange title but I'm having a difficult time thinking of something more descriptive.
I need to know how you'd accomplish the following thing in T-SQL:
Imagine you have the following 3 tables with the typical 1-to-many relationships you'd expect for these entities. Notice though "SpecialBooleanFlag" on ... | 2 words, CROSS APPLY.
```
IF OBJECT_ID('tempdb..#Customers') IS NOT NULL DROP TABLE #Customers
IF OBJECT_ID('tempdb..#Orders') IS NOT NULL DROP TABLE #Orders
IF OBJECT_ID('tempdb..#Items') IS NOT NULL DROP TABLE #Items
CREATE TABLE #Customers ( CustomerId INT, CustomerName varchar(255) )
CREATE TABLE #Orders ( OrderI... | I think something like this should work:
```
SELECT c.CustomerName, c.CustomerId, o.OrderId, i.ItemDescription, i.SpecialBooleanFlag
FROM Customers c
LEFT JOIN Orders o on c.CustomerId = o.CustomerId
LEFT JOIN Items i on o.OrderId = i.OrderId OR EXISTS
(SELECT 1 FROM orders o1 JOIN items i1 ON o1.OrderId = i1.Orde... | t-sql Odd Join Requirement | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have this table
```
User | SecretId | Status
warheat1990 | NULL | REV
warheat1990 | NULL | COM
warheat1990 | 1 | REV
warheat1990 | 1 | COM
```
I want to filter out data with (Status = REV and SecretId IS NOT NULL combined) so the final result will be
```
User | Secre... | I think you should use OR in your SQL:
```
SELECT * FROM TABLE WHERE User = 'warheat1990' AND (Status <> 'REV' OR SecretId IS NULL)
```
Here is the math knowledge: you want to match the condition "not (A and B)", then you can use the equivalent expression ((not A) or (not B)), so you should use OR instead of AND. | So you want to return data where `Status <> 'REV'` **OR** `SecretId IS NULL`:
```
SELECT *
FROM TABLE
WHERE User = 'warheat1990' AND
(Status <> 'REV' OR SecretId IS NULL)
```
When you are using `AND` you get only those rows that satisfy both conditions. When you are using `OR` you get the rows that match at le... | Filter where on condition | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
The below query takes several minutes(never completes sometimes) to execute. I'm using `MySQL` database.
```
select
customer_name as cust,
SUM(num_visits) AS visits
from
visit_history
where
category = "middleMan"
and eve_date >= '2014-07-01' and eve_date <= '... | Here's another way using a derived table
```
select
customer_name as cust,
sum(num_visits) as visits
from visit_history
join (
select distinct eve_name from master_type_ahj
where category = "middleMan"
and eve_date >= '2014-07-01'
and eve_date <= '2015-07-01'
) t on t.eve_name = visit_hist... | MySQL often handles `EXISTS` better than `IN`. So, this is your query:
```
select customer_name as cust, SUM(num_visits) AS visits
from visit_history
where category = 'middleMan' and
eve_date >= '2014-07-01' and eve_date <= '2015-07-01 and
eve_type = 'XCG' and
exists (select 1
from mast... | SQL subquery causing overall query to go slow | [
"",
"mysql",
"sql",
"sql-tuning",
""
] |
I have the following ODBC query from SSRS to a MySQL database:
```
SELECT ID, StartTime, StartTimeMS, EndTime, EndTimeMS, TIMEDIFF(EndTime, StartTime) AS CallDuration, CallType, CallerID, DialedNumber, Extension
FROM `call`
WHERE (CallerID = ?) OR
(Extension = ?) AND (StartTime < ?) A... | I don't think you can pass named parameters to MySQL like that but I think you can create them in the query:
```
SET @number = ?
SET @EndDate = ?
SET @BeginDate = ?
SELECT ID, StartTime, StartTimeMS, EndTime, EndTimeMS, TIMEDIFF(EndTime, StartTime) AS CallDuration, CallType, CallerID, DialedNumber, Extension
FR... | Name the parameters:
```
SELECT ID, StartTime, StartTimeMS, EndTime, EndTimeMS, TIMEDIFF(EndTime, StartTime) AS CallDuration, CallType, CallerID, DialedNumber, Extension
FROM `call`
WHERE (CallerID = @number) OR
(Extension = @number) AND (StartTime < @EndDate) AND (StartTime > @BeginD... | Can I use an ODBC parameter twice? | [
"",
"mysql",
"sql",
"reporting-services",
"odbc",
""
] |
I have this sql query
```
SELECT SUM(DATEDIFF(MINUTE, InTime , OutTime)) /60
FROM Attendance
WHERE InTime BETWEEN '01-01-2016' AND '01-31-2016'
AND Employee=63
var AttendofEmp = (from ab in db.Attendances
where ab.InTime >= Convert.ToDateTime("01-01-2016") &&
ab.InTi... | Try using `new DateTime()` for your date constants. Additionally, you can use [**`SqlMethods.DateDiffMinute`**](https://msdn.microsoft.com/en-us/library/system.data.linq.sqlclient.sqlmethods.datediffminute(v=vs.110).aspx) to get the minute difference and `.Sum()` to get the sum:
```
var AttendofEmp =
(from a in d... | Convert `Convert.ToDateTime` to a variable and then use it in the query. | why my linq query is not giving me expected results | [
"",
"sql",
"linq",
"sql-to-linq-conversion",
""
] |
I have a table with 2 primary key columns : `ID` and `StudentID`.
`ID` column is set to `isIdentity = Yes` with auto increment.
I've tested it multiple times before, but for some reason this time, when I insert a duplicate value on `StudentID`, it does not throw the error but instead added it on to the database. 2 of... | You have a compound primary key on `ID` and `StudentID`. That means you the combination of ID and StudentID together must be unique. Since `ID` is an identity column that combination of `ID` and `StudentID` will always be unique (because `ID` is already unique on its own).
You can change the primary key to be on `ID` ... | Do not mix up identity, primary key and unique key.
1. Any table can have identity key which you can setup on table. Here seed can be say 1, then increment it by 1. So incremental order will like 1,2,3...and so on.
2. Primary key, one can define on specific column of the table. Identity key can be used as primary key.... | SQL Primary Key Duplicate Values | [
"",
"sql",
"database",
"duplicates",
"primary-key",
""
] |
I have simple sql:
```
SELECT *
FROM `oc_artists`
WHERE `oc_artists`.`artist_id`=`oc_artists_tags`.`artist_id`
AND `oc_artists_tags`.`artist_tag` LIKE '%klass%'
```
When I run this I got:
> 1054 - Unknown column 'oc\_artists\_tags.artist\_id' in 'where clause'
This is a sql for a search script. I need simple ... | 2nd join table is missing from your query, so `include oc_artists_tags` table in your join...
Finally your query should be-
```
SELECT *
FROM `oc_artists`, `oc_artists_tags`
WHERE `oc_artists`.`artist_id`=`oc_artists_tags`.`artist_id`
AND `oc_artists_tags`.`artist_tag` LIKE '%klass%'
```
You can also use join ... | You need to JOIN the table `oc_artists_tags` too and you can achieve this two way,
**Option 1**
```
SELECT *
FROM `oc_artists`
INNER JOIN `test2` on `oc_artists`.`artist_id`=`oc_artists_tags`.`artist_id`
AND `oc_artists_tags`.`artist_tag` LIKE '%klass%'
```
**Option 2**
```
SELECT *
FROM `oc_artists`,`oc_ar... | Unknown column in 'where-clause' | [
"",
"mysql",
"sql",
"where-clause",
""
] |
Let's say that I have a table containing all of my Customer records.
Each record has a unique ID, a name and possibly a parent record ID.
(In case it makes a difference a parent can have multiple children but children can only have one parent. There's also no grandfather records, so a parent may not have a parent an... | You probably need to use a [recursive common table expression](https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx) to iterate through the ancestry and get all related records:
```
DECLARE @CustomerID INT = 100;
-- SAMPLE DATA FOR CUSTOMERS
DECLARE @Customers TABLE (ID INT, Name VARCHAR(255), ParentI... | ```
Select tickets.Description
FROM
Tickets AS tickets
LEFT JOIN
Customers ON
customers.ID= tickets.ParentID
OR
customers.ParentID =tickets.ParentID
WHERE
Tickets.ParentID = 100
``` | Select Ticket records from one table that are associated with a Customer or the Customers children in another table | [
"",
"sql",
"select",
"sql-server-2008-r2",
""
] |
I have the following table `tableA` in PostgreSQL:
```
+-------------+-------------------------+
| OperationId | Error |
+-------------+-------------------------+
| 1 | MajorCategoryX:DetailsP |
| 2 | MajorCategoryX:DetailsQ |
| 3 | MajorCategoryY:DetailsR |
+-----------... | Assuming the length before the `:` can vary you could use `substring` in combination with `strpos` to achieve your results:
```
SELECT
SUBSTRING(error, 0, STRPOS(error, ':')) AS Category,
COUNT(*) AS ErrorCount
FROM t
GROUP BY SUBSTRING(error, 0, STRPOS(error, ':'))
```
[Sample SQL Fiddle](http://www.sq... | `split_part()` seems simplest ([as @ub3rst4r mentioned](https://stackoverflow.com/a/36671167/939860)):
* [Cut string after first occurrence of a character](https://stackoverflow.com/questions/29522829/cut-string-after-first-occurrence-of-a-character/29522894#29522894#)
But you don't need a subquery:
```
SELECT split... | How to group on part of a column in PostgreSQL? | [
"",
"sql",
"postgresql",
"aggregation",
"string-matching",
""
] |
I have two tables `debitTable` and `creditTable`.
`debitTable` has the following records:
```
+----+-------+
| id | debit |
+----+-------+
| a | 10000 |
| b | 35000 |
+----+-------+
```
and `creditTable` has these records:
```
+----+--------+
| id | credit |
+----+--------+
| b | 5000 |
+----+--------+
```
Ho... | You want to use a `join`. However, it is important to aggregate before joining:
```
select coalesce(d.id, c.id) as id, coalesce(credit, 0) as credit,
(coalesce(debit, 0) - coalesce(credit, 0)) as DebitMinusCredit
from (select id, sum(debit) as debit
from debit
group by id
) d full outer join
... | You can try "Left Join"
```
Select *
from debit d
left join credit c on d.id = c.id
``` | SQL query for insert into with update on duplicate key | [
"",
"sql",
"sql-server",
""
] |
Given the table structure:
```
Comment
-------------
ID (PK)
ParentCommentID (FK)
```
I want to run `DELETE FROM Comments` to remove all records.
However, the relationship with the parent comment record creates a FK conflict if the parent comment is deleted before the child comments.
To solve this, deleting in reve... | The following will delete all rows that are not themselves parents. If the table is big and there's no index on ParentCommentID, it might take a while to run...
```
DELETE Comment
from Comment co
where not exists (-- Correlated subquery
select 1
from Comment
... | With separate Parent and Child tables, ON DELETE CASCADE would ensure that deleting the parent also deletes the children. Does it work when both sets of data are within the same table? Maybe, and I'd love to find out!
[How do I use cascade delete with SQL server.](https://stackoverflow.com/questions/6260688/how-do-i-u... | SQL delete records in order | [
"",
"sql",
"sql-server",
"sql-delete",
""
] |
have 3 tables
*product\_tags*
```
product_id | tag
___________________
50 | new
50 | blac
66 | new
50 | green
111 | new
111 | white
```
*products\_to\_categories*
```
product_id | category_id
____________________
50 | 69
50 | 68
111 | 40
111 ... | Do this step by step. Use `EXISTS` or `IN` when checking whether a record exists. You want product\_ids that are in the set of category\_ids 68 and its children:
```
select tag, count(*)
from product_tags
where product_id in
(
select product_id
from products_to_categories
where category_id = 68
or category_id ... | First, your `Join` on categories was incorrect. It should be:
```
LEFT JOIN categories optx ON optx.parent_id = optc.category_id
```
Then to get the correct `count()` you should do a `GROUP BY` tag:
```
SELECT CONCAT(opd.tag, ' (', count(*), ')' )
FROM product_tags opd
LEFT JOIN products_to_categories optc ON op... | Mysql multi join with count | [
"",
"mysql",
"sql",
"join",
"count",
""
] |
i need advice how to get fastest result for querying on big size table.
I am using SQL Server 2012, my condition is like this:
I have 5 tables contains transaction record, each table has 35 millions of records.
All tables has 14 columns, the columns i need to search is GroupName, CustomerName, and NoRegistration. And ... | Ok, so you don't need to make those new tables. If you create Non-Clustered indexes based upon these fields it will (in effect) do what you're after. The index will only store data on the columns that you indicate, not the whole table. Be aware, however, that indexes are excellent to aid in SELECT statements but will n... | You must show sql of TransactionRecords\_view. Do you have indexes? What is the collation of NoRegistration column? Paste the Actual Execution Plan for each query. | Fastest execution time for querying on Big size table | [
"",
"sql",
"sql-server",
"sqlperformance",
""
] |
i have a list of number in mysql like that
```
column 1 column2 column 3
4
6
7
88
21
29
30
31
```
How can i get all sequential blocks, result should be
```
6
7
29
30
31
``` | This is one way to it using self-join and `union`.
```
select t1.val
from t t1
join t t2 on t1.val = t2.val-1
union
select t2.val
from t t1
join t t2 on t1.val = t2.val-1
order by 1
```
Edit: I realized this could be done with a single query instead of using `union`.
```
select distinct t1.val
from t t1
join t t2 on... | You can use `exists`:
```
select t.*
from t
where exists (select 1
from t t2
where t2.col1 = t.col1 + 1
) or
exists (select 1
from t t2
where t2.col1 = t.col1 - 1
) ;
```
You can combine the `exists` into a single subquery:
```
s... | Get all sequential block from a list | [
"",
"mysql",
"sql",
""
] |
I've created a SQL Fiddle (<http://sqlfiddle.com/#!9/e0536/1>) with similar data I've got at work (there are actually more columns in the table). Table contains employment details. An employee can have more than one record in the table (couple of fixed-term contracts) as well as different employee\_ID (change from 'tix... | probably you looking for query like this:
```
SELECT e.*, CASE WHEN actual = StartDate THEN 1 ELSE 0 END AS actual_e, first_startdate
FROM Employees AS e
INNER JOIN(SELECT PESEL, MIN(startdate) AS first_startdate , MAX(startdate) AS actual
FROM Employees AS e
GROUP BY PESEL) AS g
ON g.PESEL = e.PESEL
```
EDIT:... | ```
SELECT e1.employee_id, e.pesel, e.maxdate
FROM (
SELECT pesel, MAX(expirationdate) as maxdate
FROM employees
GROUP BY pesel
) e
INNER JOIN employees e1
ON e.pesel = e1.pesel AND e.maxdate = e1.expirationdate
```
Output:
```
| Employee_ID | pesel | maxdate |
|-------------|----... | SQL WHERE MAX(date) within GROUP BY | [
"",
"sql",
"sql-server-2008",
""
] |
I have a query that takes roughly four minutes to run on a high powered SSD server with no other notable processes running. I'd like to make it faster if possible.
The database stores a match history for a popular video game called Dota 2. In this game, ten players (five on each team) each select a "hero" and battle i... | In all likelihood, the main performance driver is the `GROUP BY`. Sometimes, in MySQL, it can be faster to use correlated subuqeries. So, try writing the query like this:
```
SELECT m.match_id,
(SELECT SUM(h.xp_from_wins / h.team_xp_from_wins)
FROM matches_heroes mh INNER JOIN
heroes h
... | As has already been mentioned in a comment; there is little you can do, because you select all data from the table. The query looks perfect.
The one idea that comes to mind are covering indexes. With indexes containing all data needed for the query, the tables themselves don't have to be accessed anymore.
```
CREATE ... | Please help me optimize this MySQL SELECT statement | [
"",
"mysql",
"sql",
"sql-tuning",
""
] |
I am trying to get the next value from this filed `SU - 1 /2016`
Query I used
```
SELECT RIGHT('000' + CAST(ISNULL(MAX(SUBSTRING(InvoiceNO,4, 1)), 0) + 1 AS VARCHAR(4)), 4)
from [dbo].[Invoice]
```
The query output is `0001`, it should be `0002`. | You substring this value `SU - 1 /2016` from 4th position which gives you "-". So to get the 1 you need to start from 6th position which gives you expected output.
```
SELECT
RIGHT('000' + CAST(ISNULL(MAX(SUBSTRING(InvoiceNO,6, 1)), 0) + 1 AS VARCHAR(4)), 4)
from [dbo].[Invoice]
``` | **use this code.**
```
SELECT RIGHT('000' + CAST((ISNULL(MAX(SUBSTRING(exampleColumn,6, 1)), 0) + 1) AS VARCHAR(4)), 4)
from [dbo].tblExample
```
You have take a char from 4th position but your data "1" is at 6th position. | Getting next value from sequence sql | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have this schema.
```
create table "user" (id serial primary key, name text unique);
create table document (owner integer references "user", ...);
```
I want to select all the documents owned by the user named "vortico". Can I do it in one query? The following doesn't seem to work.
```
select * from document where... | ```
SELECT * FROM document d INNER JOIN "user" u ON d.owner = u.name
WHERE u.name = 'vortico'
``` | You can use subquery. For your example it can be faster
```
SELECT * FROM document WHERE
owner = (SELECT id FROM users WHERE name = 'vortico');
``` | Use WHERE clause on a column from another table | [
"",
"sql",
"postgresql",
""
] |
This is the given table:
[](https://i.stack.imgur.com/lfgDT.png)
I need to get this data without creating temporary table based on the above table:
[](https://i.stack.imgur.com/PcNq... | Try this
```
SELECT company name,'No' as value, clicks as data
from table1
union all
SELECT company,'Yes', (clicks - impression)
from table1
order by name,val
``` | You can use `UNION ALL` to unpivot your table:
```
SELECT
company,
'No' AS val,
impression AS data
FROM tbl
UNION ALL
SELECT
company,
'Yes' AS val,
clicks - impression AS data
FROM tbl
ORDER BY company, val
``` | disply two rows from single row | [
"",
"sql",
""
] |
I would like to sum only the last 2 weeks for each user and GROUP BY User.
MY TABLE:
```
+----+------+--------+------+
| ID | User | Income | Week |
+----+------+--------+------+
| 1 | John | 50 | 1 |
+----+------+--------+------+
| 2 | John | 20 | 2 |
+----+------+--------+------+
| 3 | John | 25 ... | You could use a row\_number() to sort out the top two weeks for a given user. Thereafter, you could aggregate. Works in postgresql.
```
Select user, sum(income)
from(
select user, income, row_number() over (partition by user order by week desc) rn
from your_table
)
where rn<3 group by user;
``` | MySql---
```
SELECT User,Sum(Income) as Income
FROM mytable
WHERE week > (SELECT MAX(week) FROM mytable) - 2
GROUP BY User
```
[sqlfiddle](http://sqlfiddle.com/#!9/bf327/3)
PostgreSQL---
```
SELECT "user",Sum(Income) as Income
FROM mytable
WHERE week > (SELECT MAX(week) FROM mytable) - 2
GROUP BY "user"
```
[sqlfi... | SUM AND GROUP BY WITH LIMITED ROWS | [
"",
"sql",
"postgresql",
""
] |
For a given search string **s**, I want to find values from an indexed varchar(255) field (~1m rows), so that s.startsWith(value) == true.
Example:
**s** = "hello world"
matches: "h", "hello", "hello world"
Is that possible? | You can use [`INSTR`](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_instr) with opposite arguments than one would do in most cases:
```
SELECT *
FROM mytable
WHERE INSTR('hello world', mycol) = 1
```
This will return records where *mycol* has a substring of "hello world" starting at positio... | You want to use `like` for this:
```
where col like 'hello%' -- or whatever
```
or
```
where col like concat(@s, '%')
```
The reason for using `like` is that it can make use of an index, because the pattern does not start with wildcard characters.
EDIT:
I might have the logic backwards. If so, you can still use l... | Find values that are start of SearchString | [
"",
"mysql",
"sql",
""
] |
I am trying to do a simple SQL Query (Oracle) that consists of two tables, "Revised" and "Projected". I would like to always pull records from the "Revised" table, if present. If the revised table is blank, then I need to pull from the "Projected" table. The different join combinations I have been trying do not return ... | Have you tried something like this?
```
select your columns
from revised
union all
select your columns
from projected where not exists (select 1 from revised);
```
Select all from revised and all from projected if there is nothing in revised.
Or, without `exists`:
```
select your columns
from revised
union all
s... | You can use case and a left join to achieve this.
```
select p.Project_ID,
case when r.Project_ID is null then p.ProjectedPaymentAmount else r.RevisedPaymentAmount end as PaymentAmount,
case when r.Project_ID is null then p.ProjectedPaymentDate else r.RevisedPaymentDate end as PaymentDate
from ProjectPayments... | SQL Two tables, need to pull depending on what data is in each | [
"",
"sql",
"oracle",
""
] |
Firstly my sql:
```
SELECT DISTINCT(CarTable.CarPlate), CarTable.CarImage, EventTable.FirstDate
FROM CarTable JOIN EventTable ON CarTable.CarId = EventTable.CarId
ORDER BY 3 DESC
```
I am trying order rows by date and that works fine but I want all plates to be written only one time. I mean I need to see all car's la... | Use `MAX` and `GROUP BY`:
```
SELECT
c.CarPlate,
c.CarImage,
FirstDate = MAX(e.FirstDate)
FROM CarTable c
INNER JOIN EventTable e
ON c.CarId = e.CarId
GROUP BY c.CarPlate, c.CarImage
ORDER BY MAX(e.FirstDate) DESC
```
Note:
* Use meaningful alias to improve readability. | see,if this work without using aggregate function.
```
SELECT c.CarPlate
,c.CarImage
,ev.FirstDate
FROM CarTable C
CROSS APPLY (
SELECT max(FirstDate) FirstDate
FROM EventTable E
WHERE c.CarId = e.CarId
) ev
ORDER BY ev.FirstDate DESC
``` | Order by with distinct | [
"",
"sql",
"sql-server",
"sql-order-by",
"distinct",
""
] |
I have 5 databases(or schemas) which have more than 100 tables in MySQL and now I need to create new database which have tables like older tables.
New tables' names are in this format
> **"OldDatabaseName"\_"OldTableName"\_History**
and their columns are almost same, just I need to add 2 new columns like **START** an... | "Are there any loop through solution for this?"
Yes.
write a stored procedure and:
* Declare Variables, Cursor and Exception\_Handler (we use the Exception\_Handler to find an exit point for our loop)
* load all schema\_names/table\_names from information\_schema.tables that
should be duplicated into the cursor (... | first create the table using this one
```
create table new_table select * from old_table;
```
and then use alter table query to alter your wish | Mysql create tables like other tables | [
"",
"mysql",
"sql",
"database",
"create-table",
""
] |
Below is my query, I think in principle it should work, but am not sure if it is indeed possible or I am thinking too outside the box for this one.
```
SELECT
(SELECT `orders`.`Status`, COUNT(*) AS COUNT_2 FROM `orders` `sw_orders` WHERE STATUS = 'booking' AND Date(OrderDate) <= CURDATE() AND Date(OrderDate) > DATE... | ```
SELECT count(case when STATUS = 'booking' then 1 end) /
count(case when STATUS = 'quote' then 1 end)
FROM `sw_orders`
WHERE Date(OrderDate) <= CURDATE()
AND Date(OrderDate) > DATE_SUB(CURDATE(),INTERVAL 30 DAY)
``` | ```
select count(status ='booking' or null) / count(status = 'quote') as result from table_name where Date(OrderDate) <= CURDATE() AND Date(OrderDate) > DATE_SUB(CURDATE(),INTERVAL 30 DAY)
```
Please watch out for syntax error. I have not taken care of. | I am trying to divide two select queries using sql, not sure if this is possible or not | [
"",
"mysql",
"sql",
""
] |
I have this function which is used on my view.
```
FUNCTION [dbo].[CalculateAmount] (
@ID INT,
@PRICE DECIMAL(24,4))
declare @computedValue decimal(24,4)
set @computedValue = case when
(select TABLE1.ID
FROM dbo.[TABLE1] TABLE1
JOIN dbo.[TABLE2] TABLE2 ON TABLE2.ID = TABLE1.ID
WHERE TABLE1.ID = @ID // some conditi... | If the only place you use your function is in the view, then why not just encapsulate the logic in the view:
```
ALTER VIEW dbo.YourView
AS
SELECT <columns>,
CalculatedPrice = CASE WHEN t1.ID IS NULL THEN <tables>.Price
ELSE 1.0368 * <tables>.Price
... | From performance point of view,knowing more details is important.
i ) first of all,it is known fact that UDF always degrade performance specially when it fire for lot of rows.
ii) What is written inside view.May be your requirement can be adjusted inside view itself,so no need of function of any kind.
like you side ... | SQL function performance | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
Is it possible to retrieve specific columns of specific rows in an `SQL query`?
Let's say I'm selecting from my `SQL` table, called `my_table`, rows whose names are: a, b, using this query text:
```
"select * from my_table where row_names in ('a', 'b') order by row_names"
```
How can I modify this query text to sele... | Replace the wildcard symbol `*` with the column names you want to retrieve.
But please read up the documentation on SQL standard. It is very unlikely you need 1.000 columns in a table. | Try and read the sql, as it really does what it says
```
select [column name 1, column name 2]
from [table name]
where [column name 3] in ('column value 1', 'column value 2')
order by [column name 3]
```
please select the values of "column name 1" and "column name 2"
from rows in the table called "table name"
where... | Select specific rows and columns from an SQL database | [
"",
"mysql",
"sql",
""
] |
My question in kind of replace with key in SQL Server. Can anyone give me a query to do this?
Thanks for your answers!
`Table1`:
```
ID | Code | Des | more columns
---+------+-----+-------------
1 | 100 | a | ...
2 | 200 | b | ...
3 | 300 |data3| ...
```
`Table2`:
```
ID | Code | ... | Do a `LEFT JOIN`, if there are no table2.Des value, take table1.Des instead:
```
select t1.ID, t1.Code, coalesce(t2.Des, t1.Des), t1.more Column
from table1 t1
left join table2 t2 on t1.code = t2.code
```
Or, perhaps you want this:
```
select * from table2
union all
select * from table1 t1
where not exists (select 1... | Use `JOIN`.
**Query**
```
SELECT t1.ID, t1.Code,
CASE WHEN t1.Des LIKE 'data%' THEN t1.Des ELSE t2.Des END AS Des
FROM Table1 t1
LEFT JOIN Table2 t2
ON t1.ID = t2.ID;
``` | Replace Data With Key on 2 table in SQL Server | [
"",
"sql",
"sql-server",
""
] |
I have a table of employees that describe his last and first name, his Card ID and times he log in to an enterprise. I want to select the first time he logs in.
thise is a example of the table
[thise is a example of the table](https://i.stack.imgur.com/Po00h.png)
and this is the result that I want
[this is the resul... | You could group by the last name, first name and truncated date and return the minimal date per group. In modern SQL Server versions this truncation is pretty simple - you just cast the `field_time` to a `date`:
```
SELECT last_name,
first_name,
CAST(field_time AS DATE) AS log_day,
MIN(fie... | I maintain table design is bad.
try this,
```
insert into @t values(1, 'A.','A.','01.01.2016 10:20:00')
,(2,'A.','A.','01.01.2016 12:22:00')
,(3,'A.','A.','03.01.2016 08:50:00')
,(4,'B.','B.','01.01.2016 15:08:00')
;WITH CTE
AS (
SELECT *
,row_number() OVER (
PARTITION BY lastn... | Select the first log in Time using from Table using SQL Server 2008 R2 | [
"",
"sql",
"sql-server",
"select",
""
] |
Apologies in advance if this is an easy solution but since I'm not sure what to call this I didn't have any luck trying to search for it.
Given the following example data:
```
ID, QUANTITY, Date
1,2,01-APR-16
1,1,02-APR-16
1,0,03-APR-16
1,1,04-APR-16
1,0,05-APR-16
1,1,06-APR-16
1,0,07-APR-16
```
I would like a query... | Suppose your table is called t. I changed column name "date" to "dt" - don't use reserved Oracle words as column names.
```
with a as (select id, max(dt) max_dt from t where quantity > 0 group by id)
select id, dt from t join a using (id) where quantity = 0 and t.dt < a.max_dt
```
ADDED: OP asked for an additional co... | Another solution using a subquery rather than a temporary table might look like
```
select t1.id, t1.dt from t t1, (select id, max(dt) max_dt from t where quantity>0 group by id) t2
where t1.id=t2.id and t1.dt < t2.max_dt and t1.quantity =0
```
I too changed the column names to match those given by mathguy.
UPDATE... | Limiting query results based upon data returned in the same query? | [
"",
"sql",
"oracle",
""
] |
Here is a table called posts\_votes
```
id|discussion_id|post_id|user_id|vote_sign|
__________________________________________
1 | 1 | 1 | 1 | 1 |
2 | 1 | 1 | 2 | -1 |
3 | 1 | 2 | 3 | 1 |
4 | 1 | 2 | 4 | 1 |
5 | 2 ... | Use sub-queries to first calculate the scores and select max score for each discussion\_id. Then `join` the result sets to get the post with max score for each discussion\_id.
```
select t1.*
from (select discussion_id,post_id,sum(vote_sign) as score
from posts_votes
group by discussion_id,post_id) t1
join... | ```
select SUBSTRING_INDEX(GROUP_CONCAT(post_id ORDER BY sm DESC), ',', 1) AS top_post, discussion_id, max(score) as score
from (
select discussion_id, post_id, sum(vote_sign) as score
from posts_votes
group by post_id, discussion_id
) c
group by discussion_id
``` | MYSQL Multi group by and max | [
"",
"mysql",
"sql",
"sum",
"max",
""
] |
SQL Server 2005. I am **not** after a coded answer here (although it would be nice). I'm really after advice on the best way forward to get the result I need. I have some knowledge of pivot/unpivot/cte//rownumber and dynamic queries but cannot get my head around this particular problem! An example of the data follows. ... | Your goal seem to select all distinct value of all columns, then Concatenate into one string. And you only need advice, so I recommend you go here: [multiple rows into a single row](https://www.mssqltips.com/sqlservertip/2914/rolling-up-multiple-rows-into-a-single-row-and-column-for-sql-server-data/)
It seem that you ... | This is slightly unrelated, but when inserting data like this it would be easier (for you) to do it like this (also, try to get into the habit of naming the fields you are inserting into);
```
INSERT INTO #temp (event, type, locations, name, description)
VALUES (1,'support','r1','fred','desc 1')
,(1,'support','r1','fr... | SQL - advice on grouping | [
"",
"sql",
"sql-server-2005",
""
] |
Here is my tables [](https://i.stack.imgur.com/N2b6r.jpg)
My question is How to get CourseNames for a specific student id
I tried this but didn't work
```
select Course.CourseName from Course
where Course.CourseId in (
select Student.studentname ,S... | I'm using left joins just in case your student doesn't have any courses assigned, otherwise, if you use inner joins, you'll get no results;
```
SELECT
s.StudentID
,s.StudentNam
,sc.CourseID
,c.CourseName
FROM Student s
LEFT JOIN StudentCourse sc
ON s.StudentID = sc.StudentID
LEFT JOIN Course c
ON sc.CourseID = c.Cours... | As you said you want to know the approach this is just basic viewpoint
1) We want to look at CourseName's.
```
SELECT CourseName FROM Course
```
2) One Student may have more than one Courses.
3) So we have one more table which is StudentCourse to achieve this.
4) We have to look CourseName's ID'S in this table
```
... | How to query for many to many relationship in Sql Server | [
"",
"sql",
"sql-server",
"select",
""
] |
i have postgresql db with a table t1 and i want to calculate a threshold.
the threshold should be for example car 1 uses more fuel than 75 % of all cars, car2 uses more fuel than 50% of all cars, ....
mathematically i understand what i want to do, but i dont know how to build the query
```
id | name | value | threshol... | You can solve this quite elegantly with a [window function](http://www.postgresql.org/docs/current/static/functions-window.html):
```
UPDATE t1
SET threshold = sub.thr
FROM (
SELECT id, 100. * (rank() OVER (ORDER BY value) - 1) / count(*) OVER () AS thr
FROM t1) sub
WHERE t1.id = sub.id;
```
The `rank()` function... | ```
WITH q AS
(
SELECT *,
(RANK() OVER (ORDER BY value) - 1) * 100. / COUNT(*) OVER () nt
FROM mytable
)
UPDATE mytable
SET threshold = nt
FROM q
WHERE mytable.id = q.id
``` | PostgreSQL calculate threshold query | [
"",
"sql",
"postgresql",
"math",
"window-functions",
"threshold",
""
] |
I have a requirement for a query. It needs to select every number from a list that IS NOT present in a column. Currently, I have this working fine. This query returns every number between `1833` and `2000` that is not present in the `ATTR` table.
```
SELECT LEVEL + 1833
FROM DUAL
CONNECT BY LEVEL <= (2000 - 1833)
MI... | How about using : as prompt ?
```
SELECT LEVEL + :STARTING_ID
FROM DUAL
CONNECT BY LEVEL <= :LIST_LENGTH
MINUS
SELECT ID_TX
FROM ATTR
WHERE ID_TX BETWEEN :STARTING_ID AND :STARTING_ID + :LIST_LENGTH;
```
This employs the concept of bind variables. Thus, user could enter the necessary values and proceed.
[![ente... | A bit of a fudge but if you want the prompt for substitution variables then you can use bind variables but just populate them using substitution variables like this:
*(Run it as a script using `F5` and not as a statement using `Ctrl+Enter`)*
```
VARIABLE list_length NUMBER;
VARIABLE start_value NUMBER;
BEGIN
:list... | Using a temporary variable once in Oracle SQL Developer | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
""
] |
I want to get row from based on parameter value. Either it could be value 'ABC' or NULL. Below is the source table and expected result, which I'm trying to achieve.
**SourceTable**
```
column1 column2
--------------------------
value1 NULL
value2 ABC
```
Tried with query, but it is getting... | You can try something like: Only problem you might encounter with this is if your column2 has blanks.
```
SELECT *
FROM SourceTable
WHERE ISNULL(column2, '') = ISNULL(@Param1, '')
``` | Perhaps this would work for you?
```
select *
from SourceTable
where column2 = @Param1 or (@Param1 is null and column2 is null)
``` | Get row from table based on parameter | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a table tblsumDemo with the following structure
```
billingid qty Percent_of_qty cumulative
1 10 5 5
2 5 8 13(5+8)
3 12 6 19(13+6)
4 1 10 29(19+10)
5 2 11 40(11+10)
``... | You can use `CROSS APPLY`:
```
SELECT
t1.*,
x.cumulative
FROM tblSumDemo t1
CROSS APPLY(
SELECT
cumulative = SUM(t2.Percent_of_Qty)
FROM tblSumDemo t2
WHERE t2.billingid <= t1.billingid
)x
```
---
For SQL Server 2012+, you can use `SUM OVER()`:
```
SELECT *,
cummulative = SUM(Perce... | **You can use subquery which works in all versions:**
```
select billingid,qty,percentofqty,
(select sum(qty) from tblsumdemo t2 where t1.id<=t2.id) as csum
from
tblsumdemo t1
```
**you can use windows functions as well from sql 2012:**
```
select *,
sum(qty) over (order by qty rows between unbound... | Calculating cumulative sum in ms-sql | [
"",
"sql",
"sql-server",
"sql-server-2008",
"cumulative-sum",
""
] |
Here is my query:
```
SELECT AccountTitle,
CASE
WHEN SourceDocDR < 1
THEN REPLACE(CAST(SourceDocDR AS int), 0, '')
ELSE SourceDocDR
END AS 'Debit',
CASE
WHEN SourceDocCR < 1
THEN REPLACE(CAST(SourceDocCR AS int), 0, '')
ELSE SourceDocCR
END AS 'Credit'
FROM tblAccounting_GL
WHERE month... | This happens because with the `ELSE` part, the return values gets converted to `DECIMAL` *(or whatever data type `SourceDocDr` has)*. Remember that in a `CASE` expression, if the return values have different data types, they will be converted to the datatype with the higher [data type precedence.](https://msdn.microsof... | you can try like this :
Since you need blank values for zero's and negative value you select blank instead of replacing values
```
SELECT AccountTitle,
CASE
WHEN SourceDocDR < 1
THEN ''
ELSE SourceDocDR
END AS 'Debit',
CASE
WHEN SourceDocCR < 1
THEN ''
ELSE SourceDocCR
END AS 'Credit'
FR... | Case condition does not return desirable results | [
"",
"sql",
"sql-server",
""
] |
I have a database query like:
```
SELECT
Foo,
Foo2,
some_calc as Bar,
some_other_calc as Bar2,
From
FooBar
-- some inner joins for the calcs
GROUP BY FOO
ORDER BY Bar DESC, Bar2 DESC;
```
I want to order by database with the order query, and then group together `FOO`s so that that first grouped block contai... | ```
SELECT foo, <some calc> AS bar, bar2
FROM foobar
ORDER BY max(<some calc>) OVER (PARTITION BY foo) DESC NULLS LAST -- can't refer to bar
, bar DESC NULLS LAST -- but you can here
, foo DESC NULLS LAST;
```
`bar` does not have to be a column, can be any valid expression, even an aggregate funct... | You just want `order by`. `Group by` reduces (in general) the number of rows by aggregation.
You can accomplish this using window functions:
```
SELECT Foo, Bar, Bar2,
From FooBar
ORDER BY MAX(Bar) OVER (PARTITION BY Foo) DESC,
Foo;
``` | Postgres GROUP BY, then sort | [
"",
"sql",
"postgresql",
"group-by",
"sql-order-by",
"aggregate",
""
] |
My table looks as follows:
```
author | group
daniel | group1,group2,group3,group4,group5,group8,group10
adam | group2,group5,group11,group12
harry | group1,group10,group15,group13,group15,group18
...
...
```
I want my output to look like:
```
author1 | author2 | intersection | union
daniel | adam | 2 | 9
dani... | Try below (for BigQuery)
```
SELECT
a.author AS author1,
b.author AS author2,
SUM(a.item=b.item) AS intersection,
EXACT_COUNT_DISTINCT(a.item) + EXACT_COUNT_DISTINCT(b.item) - intersection AS [union]
FROM FLATTEN((
SELECT author, SPLIT([group]) AS item FROM YourTable
), item) AS a
CROSS JOIN FLATTEN((
S... | I propose this option that scales better:
```
WITH YourTable AS (
SELECT 'daniel' AS author, 'group1,group2,group3,group4,group5,group8,group10' AS grp UNION ALL
SELECT 'adam' AS author, 'group2,group5,group11,group12' AS grp UNION ALL
SELECT 'harry' AS author, 'group1,group10,group13,group15,group18' AS grp
),
... | SQL- jaccard similarity | [
"",
"sql",
"google-bigquery",
""
] |
I am trying to filter the last entry in a table closet to a defined date and I am having difficulties. Any input is greatly appreciated. Thanks! I am running Microsoft SQL Server 2008.
Table:
```
code | account | date | amount
1 | 1234 | 2016-02-28 | 500
2 | 1234 | 2016-03-01 | 650
3 ... | Most DBMSes (including MS SQL Server) support Analytical Functions:
```
select *
from
(
select *,
row_number() -- create a ranking
over (partition by account -- for each account
order by date desc) as rn -- based on descending dates
from tab
where date <= date ... | Since no DBMS is specified, here's a kind of hacky way to do this in SQL Server. It grabs the record just before and just after the specified date:
```
select * from (
select top(1) * FROM mytable
where date >= '2016-03-31' order by date asc
) t1
union
select * from (
select top(1) * FROM mytable
where... | SQL Find Last Entry Closest to a Date | [
"",
"sql",
"sql-server-2008",
""
] |
```
Dim SALESINSERT As New SqlCommand("INSERT INTO Tbl_Sales (Sale_id, Transaction_No, Customer_id, Item_id, Amount, Date) VALUES(" _
& SalesIdMax + 1 & "," & Transaction_label.Text & "," & 1 & "," & Label4.Text & "," & TextBox1.Text & _
"," & DateTimePi... | If you always use parameterized queries then you will avoid problems with representing dates as strings.
You can use SQL parameters (I had to guess at the database column data types) for your query like this:
```
Dim salesinsert As New SqlCommand("INSERT INTO Tbl_Sales ([Sale_id], [Transaction_No], [Customer_id], [It... | Use the single quotes for the date value `",'" & DateTimePicker1.Value.Date & "')"`
Or
```
",#" & DateTimePicker1.Value.Date & "#)"
``` | Insert date into SQL Server database through vb.net | [
"",
"sql",
"sql-server",
"vb.net",
""
] |
The following query returns
> "single-row subquery returns more than one row"
```
select * from sampleTable
where
status = 'A'
and (SELECT SUBSTR(some_code_column, 1, 4) from sampleTable) = 9999
```
I need to fetch all the rows of the table where status is A and All the row... | No need for that sub-select, simply AND the conditions:
```
select * from sampleTable
where
status = 'A'
and SUBSTR(some_code_column, 1, 4) = 9999
``` | *This was before you clarified you wanted to return data that satisfies both conditions not one or the other*.
I would use a `UNION` in this scenario.
```
SELECT *
FROM sampleTable
WHERE status = 'A'
UNION
SELECT *
FROM sampleTable
WHERE SUBSTR(some_code_column, 1, 4) = 9999
```
More reading on performance here <ht... | Oracle - single-row subquery returns more than one row , Need to fetch all the rows | [
"",
"sql",
"oracle",
""
] |
I think I’m missing something obvious here. I'm tasked to duplicate a mapping that works fine, by changing ONLY the source qualifier portion.
The original mapping looks like this,
[](https://i.stack.imgur.com/XSGY8.png)
First of all, I don’t understand how the o... | It does not matter if the port names in SQ does not match with the select query fields. Only the order of ports matters. Also it only considers the ports that are connected with the next transformation. | **The reason why you are getting this issue is 2 out of the 5 ports in the Source Qualifier is not linked with the Source Definition.** This validation considers only the Source Qualifier ports you have linked with the source definition as well as the next transformation.
The funda is
1) The number of fields selected... | Output column mismatch. User defined SQL query in Source Qualifier | [
"",
"sql",
"sql-server",
"relational-database",
"informatica",
""
] |
I'm trying to extract an ID (5384) that is inside an array contained in JSON using wildcards. The problem I'm having is that the position of the ID doesn't have a fixed position for each element in that array. An example of my JSON in that array is like this (where "id":5384 could occupy different indexed positions):
... | The only way I would think of is to use the REGEXP syntax of MySQL:
```
SELECT id, json FROM PROD_APPNEXUS.dimension_json_creatives
WHERE (JSON REGEXP '("pixels":\[)?.*"id":5384') AND MEMBER_ID = 364
``` | Try:
[12.6 The JSON Data Type](https://dev.mysql.com/doc/refman/5.7/en/json.html). MySQL 5.7.8+
```
SELECT
`id`,
`json` -- Data Type JSON
FROM
`PROD_APPNEXUS`.`dimension_json_creatives`
WHERE
JSON_CONTAINS(`json`, '{"id": 5384}', '$.pixels') AND
`MEMBER_ID` = 364;
```
**UPDATE**
Using 5.6.17, one option i... | MySQL Wildcard on JSON array | [
"",
"mysql",
"sql",
"arrays",
"json",
""
] |
I want to find specific field of specific column from a particular table based on user provided value. It is unknown what value contain that specific column field.
To be clear:
```
Table1
--------------
| range|value|
--------------
| 100 |0 |
| 200 |2 |
| 300 |9 |
| 400 |15... | You can use a combination of `ORDER BY` and the `ROWNUM` pseudo column to select only the best row:
```
select value from (
select *
from table1
where range >= :p_Range
order by range
)
where rownum < 2
```
Alternatively, you can compute an explicit ordering using the `ROW_NUMBER()` analytic function and ... | ```
select value
from table1
where range = (select min(range ) from table1
where range >= :rangeparam)
``` | How can I find a particular row from a particular table? | [
"",
"sql",
"oracle11g",
""
] |
Is there a way to select pairs of values sequentially from one column in SQL?
i.e. If i have a table with one column of numbers
```
SomeID
------
1
2
3
5
7
11
```
I need to return a set of two columns like so:
```
FirstID SecondID
-------------------
1 2
2 3
3 5
5 7
7 ... | ```
SELECT
t1.SomeID as FirstID,
t2.SomeID as SecondID
FROM
(
SELECT SomeID, ROW_NUMBER()OVER(ORDER BY SomeID) as Inc
FROM TABLE
) t1
LEFT JOIN
(
SELECT SomeID, ROW_NUMBER()OVER(ORDER BY SomeID)-1 as Inc
FROM TABLE
) t2 ON t2.Inc = t1.Inc
```
works on sql server >= 2005 | You can do this with the windowed function, `LEAD` (or `LAG`)
```
;WITH My_CTE AS
(
SELECT
some_id as first_id,
LEAD(some_id, 1, NULL) OVER (ORDER BY some_id) AS second_id
FROM
My_Table
)
SELECT
first_id,
second_id
FROM
My_CTE
WHERE
second_id IS NOT NULL -- to not get 11, NULL at the end
... | SQL Server - Select pairs of values from one column | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
With Oracle dynamic SQL one is able to execute a string containing a SQL statement. e.g.
```
l_stmt := 'select count(*) from tab1';
execute immediate l_stmt;
```
Is it possible to not execute `l_stmt` but check that the syntax and semantics is correct programmitically? | I think that the only "solution" is to use `DBMS_SQL.PARSE()`.
It is not perfect but it is the best that you can get | [`EXPLAIN PLAN`](http://docs.oracle.com/database/121/SQLRF/statements_9010.htm#SQLRF01601) will check the syntax and semantics of almost all types of SQL statements. And unlike `DBMS_SQL.PARSE` it will not implicitly execute anything.
The point of the explain plan is to show how Oracle will execute a statement. As a s... | Dynamic SQL - Check syntax and semantics | [
"",
"sql",
"oracle",
"dynamic-sql",
""
] |
I would like to remove all rows from the table **EXCEPT** when `FirstName` is **Ben** and `isAdmin` is true
Here is my SQL
```
DELETE FROM Table1
WHERE (FirstName <> 'Ben' AND isAdmin = 1);
```
However, my issue is that when `isAdmin` is false... it should remove that row as well but it doesn't remove it. What is my... | The correct SQL should be
```
DELETE FROM Table1
WHERE (FirstName <> 'Ben' OR isAdmin = 0);
``` | You want:
```
DELETE FROM t
WHERE NOT (a AND b)
```
The negation of `a AND b` is `NOT a OR NOT b`
so your query should be
```
DELETE FROM Table1
WHERE NOT (FirstName = 'Ben' AND isAdmin = 1);
```
or
```
DELETE FROM Table1
WHERE FirstName <> 'Ben' OR isAdmin <> 1);
```
Personally I think the first option identifi... | Remove all rows Except condition | [
"",
"sql",
"database",
"where-clause",
""
] |
I was hoping to get some guidance on a SQL script I am trying to put together for Oracle database 11g.
I am attempting to perform a count of claims from the 'claim' table, and order them by year / month / and enterprise.
I was able to get a count of claims and order them like I would like, however I need to pull data... | You can try this. Joins can be used when calculating row numbers with `row_number` function.
```
SELECT TO_CHAR (SYSTEM_ENTRY_DATE, 'YYYY') YEAR,
TO_CHAR (SYSTEM_ENTRY_DATE, 'MM') MONTH,
ENTERPRISE_IID,
NAME,
COUNT (*) CLAIMS
FROM (SELECT CLAIM.CLAIM_EID,
CLAIM.SYSTEM_ENTRY_DATE,
CLAIM.ENTE... | I'd write the query like this:
```
SELECT TO_CHAR(TRUNC(c.system_entry_date,'MM'),'YYYY') AS year
, TO_CHAR(TRUNC(c.system_entry_date,'MM'),'MM') AS month
, e.enterprise_name AS name
, COUNT(*) AS claims
FROM (
SELECT r.c... | SQL NOOB - Oracle joins and Row Number | [
"",
"sql",
"database",
"oracle",
"join",
""
] |
I have a view like this:
```
ID| Key | Product | Item | Block | Source | Title | Text | Type | H1 | H2 | H3 |
-------------------------------------------------------------------------------
1 | 456 | abcd | def | 1 | TP | QWERT | YUIP | tgr | A1 | A2 | A3 |
2 | 567 | fhrh | klo | 1 | GT | TREW... | Ok, I've wrapped all column names in [square brackets] because you're using reserved names (Key, Text, Type) and I like consistency, it's worth breaking this habit as soon as possible.
If your criteria is that all three columns (H1, H2, H3) need to be NULL then you'll want something like this;
```
SELECT [ID]
,[k... | If you want the comparison column by column, then use `coalesce()`:
```
select ID, Key, Product, Item, Block, Source,
(case when h1 is not null then null else title end) as title,
(case when h2 is not null then null else text end) as text,
(case when h3 is not null then null else type end) as type... | SQL Select Columns.. IF NULL then Select other Columns | [
"",
"sql",
"t-sql",
"select",
""
] |
Let's say I have a query:
```
select product_id, price, price_day
from products
where price>10
```
and I want to join the result of this query with itself (if for example I want to get in the same row product's price and the price in **previous** day)
I can do this:
```
select * from
(
select product_id, price, pr... | self join query will help
```
select a.product_ID,a.price
,a.price_day
,b.price as prevdayprice
,b.price_day as prevday
from Table1 a
inner join table1 b
on a.product_ID=b.product_ID and a.price_day = b.price_day+1
where a.price >10
``` | You could do a bunch of things, just a few options could be:
* Just let mysql handle the optimization
+ this will likely work fine until you hit **many** rows
* Make a view for your base query and use that
+ could increase performance but mostly increases readability (if done right)
* Use a table (non temporary) a... | Join query result with itself in MySQL | [
"",
"mysql",
"sql",
""
] |
I want to concatenate a select stament for AddressLine1 up to AddressLine4, PostalCode and a PhoneNo columns in sql server 2008 such that each field will begin in a new line. This is to be use for reporting purposes. Which is the best way to have this done?
Desired outcome is:
```
2 Jojo Street
Kenyon Express... | You can concatenate the required fields, and use the `char(13)+char(10)` in between them for a new line.
```
select AddressLine1 + char(13)+char(10)
+ AddressLine2 + char(13)+char(10)
+ AddressLine3 +char(13)+char(10)
+ AddressLine4 + char(13)+char(10)
+ PostalCode + char(13)+char(10)
... | You need to CONCAT the fields with the newline character of your target system, e.g. \n or CHAR(13)+CHAR(10)
eg. [this](https://stackoverflow.com/questions/31057/how-to-insert-a-line-break-in-a-sql-server-varchar-nvarchar-string) could be helpful for you | Concatenate Address field in Sql | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I working on a little web project and I was wondering what SQL I would need to use find the month with the least amount of bookings.
I have a `Booking` table:
[](https://i.stack.imgur.com/CcPPa.png)
I have a `Package` table:
[![enter image descript... | In case you are interested in seeing results 'only' for months, not taking in account years: (I.e. All reservations from any January, no matter what year):
```
SELECT MONTHNAME(Bo_Datebooked) as month, COUNT(1) as num_reservations
FROM Booking
GROUP BY month
ORDER BY num_reservations ASC
/* additionality add...
/* LI... | Use `MONTHNAME` and `GROUP BY` a `COUNT`.
```
SELECT MONTHNAME(Bo_Datebooked), COUNT(Booking_ID)
FROM Booking
GROUP BY MONTHNAME(Bo_Datebooked)
ORDER BY COUNT(Booking_ID) ASC
``` | How to retrieve the month with the least amount of bookings in MySQL? | [
"",
"mysql",
"sql",
""
] |
I have a query that needs to count the field Points. Then returns the highest value. This query does that fine however I now want to link another table 'Team(PlayerID) with Player(PlayerID), So it shows the player team details etc. I attempted to do that normally on how you would join table but keep getting errors. I a... | ```
SELECT t.*, p.* FROM
team t INNER JOIN
(SELECT PlayerID, COUNT(Points)
FROM Player
WHERE Points = 1
group by PlayerID
HAVING COUNT(Points) = (SELECT MAX(count(Points))
from Player
WHERE Points = 1
group by PlayerID)
) p
ON t.PlayerID = p... | ```
SELECT A.PlayerID, a.TotalPoints, b.[stuff]
FROM (SELECT PlayerID, COUNT(Points)
FROM Player
WHERE Points = 1
group by PlayerID
HAVING COUNT(Points) = (SELECT MAX(count(Points))
from Player
WHERE Points = 1
... | How do I use MAX and Count with two table | [
"",
"sql",
"oracle",
""
] |
In a calendar control, we can see some dates from the previous month and next month also. Sample image below
[](https://i.stack.imgur.com/PxYly.png)
```
(ie Apr-2016: Starts from Mar-28 and ends in May-08
Mar-2016: Starts from Apr Feb-29 and ends in ... | since your week is starts on Monday,you can take referece to date 0 '1900-01-01' which is a Monday. Adding 41 days would gives you your end date
```
select
date_fr = dateadd(day, datediff(day, 0, '2016-05-01') / 7 * 7, 0),
date_to = dateadd(day, datediff(day, 0, '2016-05-01') / 7 * 7, 41)
```
the follow... | Have you considered creating a dates table in your database. You would have columns for dates and a column for week number. Linking to this table you could find the week number for your start and end dates, you could then re-link to the table to find the first date of your start week and the last date of your end week.... | How to get all the dates in a full calendar month | [
"",
"sql",
"sql-server",
"t-sql",
"calendar",
""
] |
I have several hundred Hex numbers (32 char long) that were pulled from a sql db. I have them stored in an excel table and need to convert them to GUID with dashes. I have found an online converter, but it only does one at a time and this would be very time consuming (<http://www.windowstricks.in/online-windows-guid-co... | This function converts an hexadecimal String to a formatted GUID string:
```
Public Function ConvHexToGuid(hexa As String) As String
Dim guid As String * 36
Mid$(guid, 1) = Mid$(hexa, 7, 2)
Mid$(guid, 3) = Mid$(hexa, 5, 2)
Mid$(guid, 5) = Mid$(hexa, 3, 2)
Mid$(guid, 7) = Mid$(hexa, 1, 2)
Mid$(g... | The GUID to HEX is transposed as follows:
`0x00112233445566778899AABBCCDDEEFF`
`{33221100-5544-7766-8899-AABBCCDDEEFF}` | Convert a Hex number to a GUID with dashes | [
"",
"sql",
"excel",
"vba",
""
] |
I have three tables: Calendar, Employees, Task.
Employees usually complete their tasks during the week and they don't work during the weekend. What I want to accomplish, is join the tables so I will see every day in a year even if no employee completed any task.
Here is an sql that works for me:
```
SELECT c.date, t.... | The other answer here is right. Turn the inner join into a left join to return days without an employee then
```
WHERE c.date between "2016-01-01" and "2016-01-07"
AND (e.name in("John", "Rob", "Jane") or e.name is null)
``` | Change the inner join on employees to a left join, and put the name filter in the join clause, not the where clause. | How to join tables to see dates with null values? | [
"",
"mysql",
"sql",
""
] |
[sql fiddle demo here](http://sqlfiddle.com/#!6/555d4/6)
I have this table structure for Diary table:
```
CREATE TABLE Diary
(
[IdDiary] bigint,
[UserId] int,
[IdDay] numeric(18,0),
[IsAnExtraHour] bit
);
INSERT INTO Diary ([IdDiary], [UserId], [IdDay], [IsAnExtraHour])
values
(51, 1409, 1, ... | ```
SELECT d.IdDay,
MIN(CASE WHEN isAnExtraHour = 0 THEN hour END) as 'Start Time',
MAX(CASE WHEN isAnExtraHour = 0 THEN hour END) as 'End Time',
MIN(CASE WHEN isAnExtraHour = 1 THEN hour END) as 'Start Extra Time',
MAX(CASE WHEN isAnExtraHour = 1 THEN hour END) as 'End Extra Time'
FROM... | I use the code from @Quassnoi and I added this:
```
SELECT DATENAME(weekday, d.idday-1) as 'Day' ,
MIN(CASE WHEN isAnExtraHour = 0 THEN hour END) AS 'Start Time',
MAX(CASE WHEN isAnExtraHour = 0 THEN hour END) AS 'End Time',
MIN(CASE WHEN isAnExtraHour = 1 THEN hour END) AS 'Start Extra Time',
... | How I can group the results by day in this query with SQL Server? | [
"",
"sql",
"sql-server",
"time",
"group-by",
"inner-join",
""
] |
I'm very new to SQL and I don't know how to query 2 different items within the same field and the same table.
I'm writing this in Excel VBA using SQL via oledb to attach to a PostGreSQL datasource
Basically I have 2 queries that I need to combine into one query.
The first query is the primary group.
I need to first fi... | Since the column references aren't qualified, we can't tell which table each column reference refers to.
---
SUGGESTION: as an aid to future readers of the SQL, please consider qualifying *all* column references with the table name, or even better, a short (unique) table alias. Then the future reader won't be scourin... | You could try this wildcard and AND approach, to return both:
I'm assuming that `R110` might be followed by `C10..` or vice versa.
```
Dim DIAG As String
DIAG = "SELECT DISTINCT master_id, eventdate, code, term, surname, forename " _
& "FROM srch INNER JOIN person p ON master_id=p.entity_id " _
& "WHERE c... | Query 2 different items within the same field and the same table | [
"",
"sql",
"excel",
"vba",
""
] |
I have two tables `t1` and `t2`. Both have `id` and `name` columns. The name column of `t1` is defined as not null and it has the default value of 'Peter'.
I want to insert all the values from `t2` into my `t1` table. But I have some null values in `t2` table. When I try to insert the values:
```
Insert into t1
s... | First Solution,
```
insert into t1
select id,isnull(name,'Peter') from t2
```
Second solution
```
ALTER TABLE T1 ALTER COLUMN name varchar(255) NULL
insert into t1
select id,name from t2
ALTER TABLE T1 ALTER COLUMN name varchar(255) NOT NULL
``` | So instead of
```
Insert into t1 select * from t2
```
you can rewrite your query as
```
Insert into t1
select col1,col2, ISNULL(name, 'Peter'), othercolumns from t2
``` | How to set default value while insert null value into not null column SQL Server? | [
"",
"sql",
"sql-server",
"insert",
"ssms",
"default",
""
] |
Packages like `RMySQL` and `sqldf` allow one to interface with local or remote database servers. I'm creating a portable project which involves importing sql data in cases (or on devices) which do not always have access to a running server, but which *do* always have access to the latest .sql dump of the database.
**T... | depending on what you want to extract from the table, here is how you can play around with the data
```
numLines <- R.utils::countLines("sportsdb_sample_mysql_20080303.sql")
# [1] 81266
linesInDB <- readLines("sportsdb_sample_mysql_20080303.sql",n=60)
```
Then you can do some regex to get tables names (after CREATE ... | I don't think you will find a way to import a sql dump (which contains multiple tables with references) and then perform arbitrary sql queries on them within R. This would basically require the R package to run a complete database server (compatible with the one creating the dump) within R.
I would suggest exporting t... | Import MySQL dump into R (without requiring MySQL server) | [
"",
"sql",
"r",
"database",
"mysql",
""
] |
I have two tables like this:
**Table1**
```
Emp_ID Emp_Name Age Level
1 Tom 22
2 Susan 50
```
**Table2**
```
Level Min_Age Max_Age
Associate 20 30
Senior 31 45
```
What I want to do is to find which level each employee is at. As such, I w... | You shouldn't have to use a cursor at all. Just join the two tables together.
```
UPDATE t1
SET t1.[age level] = t2.level
FROM table1 t1
JOIN table2 t2 ON t1.[age level] BETWEEN t2.min_age and t2.max_age
``` | You can join- or you can use the following
```
BEGIN
for i in (select level, [min age] as MinA, [max age] as MaxA from Table2)
LOOP
Update Table1
set Table1.[age level] = i.level
where Table1.[age level] between i.MinA and i.MaxA;
END LOOP;
END
``` | Cursor through and update database record by looking for value within a range from another table | [
"",
"sql",
"sql-server",
""
] |
[](https://i.stack.imgur.com/cuwrx.png)
Hi,
I have table with row like the above picture and i would like to sum QTY of all row but i need to exclude row where AISLE = POS and QTY < 0 on the same row.
I made some try to get what i want but i can't f... | I want to note that `NOT IN` would be helpful for this query:
```
WHERE PRODUCT = 143459 AND
AISLE NOT IN ('PHY', 'RET') AND
(AISLE <> 'POS' OR QTY > 0)
```
Note: This assumes that `AISLE` is never `NULL`.
Or, alternatively:
```
WHERE PRODUCT = 143459 AND
AISLE NOT IN ('PHY', 'RET') AND
NOT ... | your second statement was almost correct, but since you are trying to "exclude AISLE = POS", then it should be `AISLE <> 'POS'`:
```
SELECT
ROUND(SUM(QTY),
2) AS INVENTORY
FROM
INV_QTY_LOCATION
WHERE
PRODUCT = 143459 AND AISLE != 'PHY' AND AISLE != 'RET' AND (AISLE <> 'POS' OR QTY > 0)
``` | MySQL - Query with grouped conditions | [
"",
"mysql",
"sql",
""
] |
**Wants to sort reviews with comment length <= 250 and >= 50**
All short or long reviews should be at the end..currently i have to filter them... but this is not what I wants to have
current query
```
select
c.id,
c.name,
DATE_FORMAT(c.created,'%d %b %Y') as date_new,
r.ratings,
c.comments,
ROUND((r.ratings_sum / r.... | In MySQL, you can do this simply using a boolean expression:
```
order by ( length(c.comments) < 50 or length(c.comments) > 250) desc
```
MySQL treats booleans in a numeric context as integers, with true as 1.
An alternative formulation is even shorter:
```
order by (length(c.comments) between 50 and 249)
``` | ```
ORDER BY
CASE
WHEN LENGTH(C.comments) > 250 OR LENGTH(C.comments) < 50 THEN 1
ELSE 0
END
``` | Sort by character length but don't want filter | [
"",
"mysql",
"sql",
"filter",
""
] |
I've got a databases table of account users. There are two types of account:-
* Administrator Account
* Standard Account
The data table has two additional columns, Account Number and Parent Account Number. Every record regardless gets assigned a new Account Number, but if an account is a Standard Account, then it get... | I think simply:
```
ORDER BY ISNULL(ParentAccountNumber, AccountNumber), ParentAccountNumber, AccountNumber
```
would do what you want. | As this is a recursive relationship a [recursive cte](https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx) could be used , or a [hierarchyId](https://msdn.microsoft.com/en-us/library/bb677290.aspx) type would / may be better. | SQL - Ordering the results of a recursive relationship | [
"",
"sql",
".net",
"sql-server",
"linq",
"t-sql",
""
] |
Can you please help me with a query that would display a table like this:
```
Dept_ID Dept_Name
10 Admin
10 Whalen
20 Sales
20 James
20 King
20 Smith
40 Marketing
... | When you union two data sets, there is NO implicit ordering, you could get the results in any order.
The get a particular order you *must* use `ORDER BY`.
To use `ORDER BY`, then you *must* have fields to do that ordering by.
In your case, the pseudo code would be...
- `ORDER BY [dept_id], [depts-then-employees], ... | ```
SELECT Dept_ID, Dept_Name
FROM Your_Table
```
Simple as I can make it. It's very difficult (near impossible) to tell exactly what the query should be without more detail in terms of your table structure and some sample data.
From your edit, you may need something more like this;
```
SELECT DT.Dept_ID, DT.Dept_Na... | What would the query be for the following sample table? | [
"",
"sql",
"union-all",
""
] |
I think this should be simple, but I can't figure it out or find a solution here.
I have a table ITEM\_PROPERTIES
```
item_ID int
property_name char(20)
property_value char(20)
```
Sample data
```
5 Colour Black
5 Size M
6 Colour Blue
6 Size L
7 Colour Purple
7 Size M
8 Colour Bl... | ```
select group_concat(concat(property_value, ' ', cnt))
from (
SELECT property_value, count(property_value) as cnt
FROM ITEM_PROPERTIES
WHERE property_name = 'Colour'
GROUP BY property_value
) c
``` | You can use two levels of aggregation:
```
SELECT group_concat(property_value, ' ', cnt separator ', ')
FROM (SELECT property_value, count(property_value) as cnt
FROM ITEM_PROPERTIES
WHERE property_name = 'Colour'
GROUP BY property_value
) ip;
``` | MySQL - count and group by - display all results in one row | [
"",
"mysql",
"sql",
"database",
""
] |
I cannot for the life of me work out a query that will take a list of Skill\_ID's and return a list of Buildings that contain a person/people with all of the skills searched for
I currently have these tables
```
Building
===========
ID | name
===========
1 | BlockA
2 | BlockB
People
============================
I... | You can do this using `GROUP BY` and `HAVING`:
```
SELECT b.Name AS Building
FROM Building b JOIN
People p
ON b.ID = p.Building_ID JOIN
SkillsToPerson sp
ON p.ID = sp.Person_ID
WHERE sp.skill_id IN (1, 2, 3) -- Skill IDs to look for
GROUP BY b.Name
HAVING COUNT(DISTINCT sp.skill_id) = 3;... | How about:
```
SELECT DISTINCT Building.Name
FROM People
INNER JOIN Building
ON Building.ID = People.Building_ID
INNER JOIN SkillsToPerson
ON SkillsToPerson.Person_ID = People.ID
INNER JOIN Skills
ON Skills.ID = SkillsToPerson.Skills_ID
WHERE Skills.Skill_ID IN (1, 2, 3, ...) -- list of skills here
``` | MSSQL - Cannot work out how to join three tables to find the building that contains people with the correct skills | [
"",
"sql",
"sql-server",
"join",
""
] |
I have been stuck for a good while on this issue now and have made zero progress. I don't even know if it is possible...
I have 1 table:
```
+------+------------+-------+---------+------------+
| Item | Date | RUnit | FDHUnit | Difference |
+------+------------+-------+---------+------------+
| A | 19/04/201... | Yes, use `union all`:
```
select item, date, ruunit, fdhunit, difference
from t
union all
select item, date, null, null, runit - fdhunit
from t
order by item, (case when runit is not null then 1 else 2 end);
```
The `order by` puts the results in the order that your results suggest. Without an `order by`, the orderin... | try this way
```
select * from
(select item, date, ruunit, fdhunit, '' as difference
from t
union all
select item, date, null as ruunit, null as fdhunit, difference
from t) a
order by item, date
``` | How to duplicate records in same table | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I have no Idea how i could solve the following problem in an effective way.
**Given**:
1.
A Telephone Number as one single String e.g.: `1111223344`
2.
A Database with this Number `split in 2 different Columns`
(First part of Number in `ColA`, Second Part of Number in `ColB`)
| The Database is huge (up to 100 GB)
L... | This should get you started. You will want to adjust this depending on the actual requirements.
If the two values are guaranteed to be strings:
```
SELECT *
FROM MyTable m
WHERE m.ColA + m.ColB = '1111223344'
```
If the two values aren't guaranteed to be strings:
```
SELECT *
FROM MyTable m
WHERE CONCAT(m.ColA, m.C... | One way i could think of is, to use Hashbytes as a computed column .you can index this column for good performance as well..
```
CREATE TABLE #TESTMAIN
(
NMBR VARCHAR(10)
)
INSERT INTO #TESTMAIN
SELECT '123456'
UNION ALL
SELECT '3456'
create table #backup
(
nmbr1 varchar(10),
nmbr2 varchar(10)
)
insert into #backup
... | SQL | Select (...) where 2 columns combined equal (xy) | [
"",
"sql",
".net",
"oracle",
""
] |
I am working on a SQL query where I have a rather huge data-set. I have the table data as mentioned below.
Existing table :
```
+---------+----------+----------------------+
| id(!PK) | name | Date |
+---------+----------+----------------------+
| 1 | abc | 21.03.2... | Seems you want the number of unique names per id:
```
insert into empty_table
select id
,count(distinct name)
,min(date)
from existing_table
where date >= DATE '2015-03-01'
and date < DATE '2015-04-01'
group by id;
``` | If I understand correctly, you just need a date condition:
```
insert into empty_table(some_id, count, date)
select id, count(*), min(date)
from existing_table
where id = 1 and
date >= date '2015-03-01' and
date < date '2015-04-01'
group by id;
```
Note: the list after the table n... | SQL : Getting data as well as count from a single table for a month | [
"",
"sql",
"database",
"teradata",
"subquery",
""
] |
Consider the following scenario :
```
an Item has a Price
a Order contains Items
a Delivery contains Orders
```
I want to query for each delivery, the order with the highest price, where a price of an order is the summation of prices of the contained items.
A simple sufficient schema would look like this :
**Deli... | Thanks for all your answers, but none of them was what i was looking for. I finally found what i was looking for and the approach i choose is as follows :
```
SELECT d_id,o_id,sum_price
FROM (
SELECT d_id,o_id,SUM(price) as sum_price
from ItemsInOrder
natural join OrdersInDelivery
natural join Item
... | You can use Left Joining with self, tweaking join conditions and filters.
In this approach, you left join the table with itself. Equality, of course, goes in the group-identifier.
```
SELECT a.*
FROM (
SELECT oid.d_id AS d_id, o_id, SUM(price) AS sum_price
FROM `OrdersInDelivery` oid
INNER JOIN... | How to find MAX over SUMs MySQL | [
"",
"mysql",
"sql",
"rdbms",
""
] |
I have a postgresql db with a number of tables. If I query:
```
SELECT column_name
FROM information_schema.columns
WHERE table_name="my_table";
```
I will get a list of the columns returned properly.
However, when I query:
```
SELECT *
FROM "my_table";
```
I get the error:
```
(ProgrammingError) relation "my_tabl... | You have to include the schema if isnt a public one
```
SELECT *
FROM <schema>."my_table"
```
Or you can change your default schema
```
SHOW search_path;
SET search_path TO my_schema;
```
Check your table schema here
```
SELECT *
FROM information_schema.columns
```
[ gets the total number of members who have more than 6 memberships....
```
select count(*) as MemberCount from (
SELECT count(membership.memberid) as MembershipCount from Membership, Package
WHERE membership.PackageId = Package.Id
AND membership.DiscountPercentag... | Try this, using your #temp.
```
select #temp.num, count(*)
from #temp
left join
(
SELECT count(membership.memberid) as MembershipCount from Membership, Package
WHERE membership.PackageId = Package.Id
AND membership.DiscountPercentage != 100
AND Package.PackageTypeId != 1
AND membership.Member... | You want to select the counts, and get the count of each of those (sounds weird, but it's actually very simple):
```
SELECT MemberCount, Count(*)
FROM
(
SELECT count(membership.memberid) as MemberCount
FROM Membership, Package
WHERE membership.PackageId = Package.Id
AND membership.DiscountP... | Outer Join SQL on having query | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I know this will cause an ambiguous error since Name exists in both tables. But
I want to select the Name from these two tables. Name is a column in t\_1 and t\_2. Is it possible to select from two tables? Is there a way for me to select the name between two tables, and returns a single column of data?
```
SELECT Name... | You could try a `UNION`;
```
SELECT Name
FROM t_1
WHERE Name LIKE '%' + @USER + '%'
UNION
SELECT Name
FROM t_2
WHERE Name LIKE '%' + @USER + '%'
```
Note, `UNION ALL` can also be used, this will also return multiple instances of the same name if they exist. Use whichever satisfies your requirements. | ```
SELECT Name
FROM t_1
WHERE Name LIKE '%' + @USER + '%'
UNION ALL
SELECT Name
FROM t_2
WHERE Name LIKE '%' + @USER + '%'
``` | Is this query possible? SELECT FROM 2 tables LIKE | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
```
+----+------+---------------------------------------+
| id | dur | workdur |
+----+------+---------------------------------------+
| 1 | 64 | /home/public/users/james/PB_3594162_0 |
| 2 | 123 | /home/public/users/john/PB_990-94162_0 |
| 3 | 13 | /doc/users/jason/PB_01251... | You can simply use aggregation together with your `WHERE` condition, with no need of a nested query:
```
select avg(dur)
from work
where workdur like '%PB_%'
``` | You can use this
```
select avg(dur)
from (select dur from work where workdur like '%PB_%');
```
**One important thing** you should notice is that in oracle (sql, in general), `_` is a wildcards like `%`, so careful with your `like` because it equal to `like '%PB%'`
So for your case you should change to (and remove... | sql: group by partial match | [
"",
"sql",
"oracle",
""
] |
I have a macro with the following code:
```
sSQL = "select [Folio Type], [Folio ID], [Departure Date]," & _
" Sum([Folio Total]), Count([Folio ID])" & _
" from [Individual Folios$B2:O150000]" & _
" group by [Folio Type], [Departure Date], [Folio ID], [Folio Total]" & _
" having Sum([... | You need to do this in two queries. I've put the second one as a subquery in the FROM clause.
```
SELECT
a.[Folio Type]
,a.[Folio ID]
,a.[Departure Date]
,b.FolioCount
,b.FolioSum
FROM
[Individual Folios$B2:O150000] a
INNER JOIN
(SELECT
[Folio ID], [Folio... | Consider inner joins of derived tables (i.e., subqueries in `FROM` clause).
Standard SQL *(conceptual illustration)*
```
SELECT t1.[Folio Type], t1.[Folio ID], t1.[Departure Date],
t2.FolioCount, t2.FolioSum
FROM
(SELECT [Folio Type], [Folio ID], [Departure Date],
[Folio Total] ... | Excel/ADO/VBA: Count returning incorrect results | [
"",
"sql",
"excel",
"vba",
"oledb",
""
] |
I'm new to SQL thus the question. I'm trying to query the following. Given the CITY and COUNTRY tables, query the names of all the continents (COUNTRY.Continent) and their respective average city populations (CITY.Population) rounded down to the nearest integer.
The table schemas are `City: id, name, countryside, popul... | Ok. Here is the solution.
```
Select Country.Continent, floor(Avg(city.population))
From Country
Inner Join City
On Country.Code = City.CountryCode
Group By Country.Continent;
```
Here, We have to group by Continent so as to have a result set for continent being the key identifier and then applying ... | ```
SELECT
COUNT(*) over (partition by c.Code)
,SUM(ci.Population)/COUNT(*) over (partition by c.Code)
FROM Country c
INNER JOIN City ci on ci.CountryCode = c.CountryCode
GROUP by c.CODE
```
I have not tested this so I apologize if it needs a little tweaking. The concept here is to group by country code since ... | Inner join and average in SQL | [
"",
"sql",
"inner-join",
"rounding",
"average",
""
] |
I have two queries that end up having the same format. Each has a Month, a year, and some relevant data per month/year. The schema looks like this:
```
subs Month Year
8150 1 2015
11060 1 2016
5 2 2014
6962 2 2015
8736 2 2016
Cans months years
2984 1 2015
27... | Without giving consideration to simplifying your queries you can use your two queries as inline views and simply select from both (I aliased Q1 and Q2 for your queries and named fields the same within each for simplicity.
```
Select Q1.cnt as Subs, Q2.cnt as Cans, Q1.months, Q1.years
from (SELECT
COUNT(personID) ... | Temporary table approach:
```
create temporary table first_query
<<your first query here>>;
create temporary table second_query
<<your second query here>>;
select fq.subs, sq.cans, fq.months, fq.years
from first_query fq
join second_query sq using (months, years)
```
Your table preview and query columns do not matc... | Correct join syntax within multiple queries and sub queries | [
"",
"mysql",
"sql",
""
] |
I have a query in which I need to get results from a table, depending on the parameters specified by the user on a vb.net page.
Declaring a variable would be the ideal solution, but since its an inline table-valued function I can't do this, I had read on other questions that this is possible in a multstatment table-fu... | First, you are correct, inline TFV is really faster. If not overcomplicated.
I'd better have a number of iTFVs for each @Periodo parameter value on the SQL Server side and choose the right one in code on the client side.
Alternatively you may do it in a single iTVF
```
WHERE
@Periodo = '0' AND CreationDate>= @fec... | You're much better off re-organising the WHERE clause, such that the filtered field is on the left had side and not inside any functions.
For example...
```
WHERE
CreationDate >= @VPeriodo
AND CreationDate < CASE
WHEN @Periodo = '0' THEN DATEADD(DAY, 1, @VPeriodo)
... | CASE inside WHERE Clause | [
"",
"sql",
"sql-server-2008",
"case",
"where-clause",
""
] |
I've used this site for many months now and it has been very helpful. However i've finally come across a problem that i've been unable to find an answer for how to do.
My table has roughly 30 columns in it but im only interested in 7 of them. What im trying to accomplish is a query which will return the date/time of t... | add one line to check make sure the appqty = 0 for an ordnum doesn't exist
```
SELECT
ordnum
,max(pckdte) AS "Last Pick"
,min(pckdte) AS "First Pick"
FROM MyTable
Where (adddte >= '2016-04-02 00:00:00' AND pckdte <= '2016-04-20 23:59:59')
and ctnnum like 'c%'
and (srcloc like '2%' or srcloc l... | Subquery should work:
```
AND ordnum not in (SELECT ordnum FROM MyTable WHERE appqty = 0)
```
This will filter out all `ordnum` that have at least one row with an `appqty` of `0`.
Full query:
```
SELECT
ordnum
,max(pckdte) AS "Last Pick"
,min(pckdte) AS "First Pick"
FROM MyTable
Where (adddte... | SQL query to return only 1 record per order based on if column does not have 0 | [
"",
"mysql",
"sql",
""
] |
If I have table like this:
```
emp_num trans_date day_type
5667 2016-03-01 1
5667 2016-03-02 1
5667 2016-03-03 1
5667 2016-03-04 3
5667 2016-03-05 3
5667 2016-03-06 1
5667 2016-03-07 1
5667 2016-03-08 1
5667 2016-03-09 1
5667 2016-03-10 1
5667 2016-03-11 3
5667 2016-03-1... | ```
DECLARE @month int = 3,
@year int = 2016
;WITH cte AS (
SELECT *
FROM (VALUES
(5667, '2016-03-01', 1),(5667, '2016-03-02', 1),(5667, '2016-03-03', 1),(5667, '2016-03-04', 3),(5667, '2016-03-05', 3),(5667, '2016-03-06', 1), --2
(5667, '2016-03-07', 1),(5667, '2016-03-08', 1),(5667, '... | Given the data provided by you:
```
declare @table1 table (emp_num int, trans_date datetime, day_type int)
insert into @table1
VALUES (5667,'2016-03-01',1),(5667,'2016-03-02',1),(5667,'2016-03-03',1),
(5667,'2016-03-04',3),(5667,'2016-03-05',3),(5667,'2016-03-06',1),
(5667,'2016-03-07',1),(5667,'2016-03-08',1),(5667,... | How to get number of days of specific type per week | [
"",
"sql",
"sql-server",
"date",
"sql-server-2012",
""
] |
I am dealing with the holiday table of a application and I have to find the next working days based on the holiday list in that table .
If the input is a working day, we expect a blank/NULL to be returned, but if it is a holiday, we expect the next working day to be returned.
My holiday table contains below sample da... | You can try this:
```
--create table holidays(y int, ds datetime, de datetime, hname varchar(10));
--insert into holidays values
--(2016,'2016-04-20 00:00:00.000','2016-04-20 00:00:00.000','Test'),
--(2016,'2016-04-21 00:00:00.000','2016-04-21 00:00:00.000','Test2'),
--(2016,'2016-04-28 00:00:00.000','2016-04-28 00:0... | Suposing a holidays table with this structure:
```
CREATE TABLE holidays (
[year] int,
[ds] datetime,
[de] datetime,
[description] nvarchar(50)
)
```
You can create a function that iterates through dates until it finds the correct one
```
CREATE FUNCTION dbo.getNextDate(@dateToCheck datetime) RETURNS... | Finding the next working day from SQL table | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
""
] |
I have two tables `[Price Range]`
```
ID | Price
1 | 10
2 | 50
3 | 100
```
and `Product`:
```
ID | Name | Price
1 | Prod1 | 5
2 | Prod2 | 10
3 | Prod3 | 20
4 | Prod4 | 30
5 | Prod5 | 50
6 | Prod5 | 60
7 | Prod6 | 120
```
I need to associate product with specific price range i.e. join both... | If `Price Range` ID's are ascending as price then you can simple:
```
SELECT p.ID,
p.Name,
MAX(pr.ID) as PriceRangeID
FROM Product p
LEFT JOIN PriceRange pr
ON p.Price >= pr.Price
GROUP BY p.ID, p.Name
```
Output:
```
ID Name PriceRangeID
----------- ----- ------------
1 Pro... | You can use this
```
select id, name, price,
(select id
from PriceRange
where price = (select max(price)
from PriceRange
where price <= a.price)
) as PriceRangeID
from Product a
``` | Sql Query to return following result set | [
"",
"sql",
"sql-server",
""
] |
I have a `product` table and every product might be `delivered`, `idle`, `shipping`, `preparing`.
I want to show a list with the counts of products for each state, and I can see how to query for that here:
[How to get multiple counts with one SQL query?](https://stackoverflow.com/questions/12789396/how-to-get-multipl... | Hard to say for sure but sounds like you need to use a version of the top answer in the link you have provided.
Something like;
```
SELECT ProductID,
COUNT(*) AS Total,
SUM(CASE WHEN pStatus = 'delivered' THEN 1 ELSE 0 END) DeliveredCount,
SUM(CASE WHEN pStatus = 'idle' THEN 1 ELSE 0 END) IdleCount,
S... | You might want to try this.
```
SELECT
SUM(CASE WHEN Prod = 'delivered' THEN 1 ELSE 0 END) as deliveredCount,
SUM(CASE WHEN Prod = 'idle' THEN 1 ELSE 0 END) as idleCount,
SUM(CASE WHEN Prod = 'shipping' THEN 1 ELSE 0 END) as shippingCount,
SUM(CASE WHEN Prod = 'preparing' THEN 1 ELSE 0 END) as preparingCount
FROM Prod... | What does a multiple count query in SQL return? | [
"",
"sql",
"sqlite",
""
] |
So I have an sql query i am currently working on that is like this:
```
SELECT * from tableA where
( status = NVL('','OPEN') or status = NVL('','CLOSED') )
and delete_flag != 'Y'
```
The above query works fine and gives me the result I want.. but I was wondering if there is anyway I can combine the above status IN N... | You are getting an input parameter from your application that can have the values "Open", "Closed" or null
You want to be able to select status values that equal this input paremeter if it is null or the value of the input if it isn't.
To have null for a filter default to all you use COALESCE and the column you are f... | simply:
```
SELECT * from tableA
where 1=1
and nvl(status, '---') IN ('OPEN','CLOSED')
and delete_flag != 'Y'
``` | sql query NVL string with apostrophes (') | [
"",
"sql",
"oracle",
"toad",
""
] |
I have a data set like this:
```
User Date Status
Eric 1/1/2015 4
Eric 2/1/2015 2
Eric 3/1/2015 4
Mike 1/1/2015 4
Mike 2/1/2015 4
Mike 3/1/2015 2
```
I'm trying to write a query in which I will retrieve users whose MOST RECENT transaction status is a 4. If it's not a 4 I don'... | ```
SELECT user, date
, actualOrders.status
FROM (
SELECT user, MAX(date) as date
FROM orders
GROUP BY user) AS lastOrderDates
INNER JOIN orders AS actualOrders USING (user, date)
WHERE actualOrders.status = 4
;
-- Since USING is being used, there is not a need to specify source of the
-- user and date fi... | ```
SELECT user, date, status FROM
(
SELECT user, MAX(date) as date, status FROM orders GROUP BY user
)
WHERE status = 4
``` | mysql highly selective query | [
"",
"mysql",
"sql",
""
] |
I have one external table like
```
CREATE EXTERNAL TABLE TAB(ID INT, NAME STRING) PARTITIONED BY(YEAR INT, MONTH STRING , DATES INT) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';
```
I have data like
```
/user/input/2015/jan/1;
/user/input/2015/jan/30
```
like that years 2000 to 2016 ,every year with 12 months an... | ```
create table tab(id int,name string,dt string) partitioned by (year string,month string);
create table samp(id int,name string,dt string) row format delimited fields terminated by '\t';
load data inpath '\dir' into table samp;
insert overwrite table tab partition (y,m) select id,name dt,YEAR(dt),MONTH(dt) from sa... | You are getting 1 day for `ALTER TABLE TAB ADD PARTITION(year = '2015', month = 'jan',dates = '5') LOCATION '/user/input/2015/jan/1';` because you are specifying 1 file in your location value
For 5 days create the partition as below
```
ALTER TABLE TAB
ADD PARTITION(dates <= '5')
LOCATION '/user/input/2015/jan/';
`... | Hive partitions by date? | [
"",
"sql",
"apache-spark",
"hive",
"hiveql",
"bigdata",
""
] |
```
table A
no date count
1 20160401 1
1 20160403 4
2 20160407 3
```
```
result
no date count
1 20160401 1
1 20160402 0
1 20160403 4
1 20160404 0
.
.
.
2 20160405 0
2 20160406 0
2 20160407 3
.
.
.
```
I'm using Oracle and I want to write a query that r... | Try this:
```
with
A as (
select 1 no, to_date('20160401', 'yyyymmdd') dat, 1 cnt from dual union all
select 1 no, to_date('20160403', 'yyyymmdd') dat, 4 cnt from dual union all
select 2 no, to_date('20160407', 'yyyymmdd') dat, 3 cnt from dual),
B as (select min(dat) mindat, max(dat) maxdat from A t),... | you can use the `SEQUENCES`.
First create a sequence
```
Create Sequence seq_name start with 20160401 max n;
```
where n is the max value till u want to display.
Then use the sql
```
select seq_name.next,case when seq_name.next = date then count else 0 end from tableA;
```
Note:- Its better not to use date,coun... | Fill in missing dates in date range from a table | [
"",
"sql",
"oracle",
"date",
""
] |
I have to provide a list of distinct sites that are active, who have one or more domain, and whose domains are all deleted. Here is my query so far.
```
SELECT DISTINCT *
FROM sites JOIN domains ON domains.site = sites.id
WHERE domains.is_deleted = 1 AND sites.is_deleted = 0
```
From my research, it seems like the b... | **Q: How can I use COUNT() to count the number of domains per site?**
(answer to the question is at the bottom of the answer.)
---
There are several different queries that will return the specified result.
I'd build the query like this, starting with
"List of distinct sites that are active"
We can get the rows fr... | To get the count of number of domains each site fulfilling the criteria :
```
SELECT DISTINCT sites.id,
sites.name,
COUNT(domains.id) AS DomainCount
FROM sites
INNER JOIN domains ON domains.site = sites.id
WHERE domains.is_deleted = 1
AND s... | count function per row | [
"",
"mysql",
"sql",
""
] |
I have a problem. It seems easy to resolve, but in fact I don't know why it is not working !
I have two tables :
```
HOSTS(id, hostgroup_id)
HOSTGROUPS(id, name)
```
With these inserted rows :
```
HOSTS
________________________
id | hostgroup_id
________________________
1 | 1
2 | 1
3 | 2
... | Try this:
```
SELECT hg.name,
(SELECT COUNT(*)
FROM HOSTS h
WHERE h.hostgroup_id = hg.id)
FROM HOSTGROUPS hg
``` | I think you can use a left join with group by
```
SELECT HG.name, COUNT(*) AS count
FROM HOSTS H
LEFT JOIN HOSTGROUPS HG ON ( H.hostgroup = HG.id)
GROUP BY HG.name;
``` | Counting rows from table | [
"",
"mysql",
"sql",
"count",
"rows",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.