Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have the following query:
```
SELECT count(*) as 'totalCalls', HOUR(`end`) as 'Hour'
FROM callsDataTable
WHERE company IN (
SELECT number
FROM products
WHERE products.id IN (@_PRODUCTS))
AND YEAR(`end`) = @_YEAR AND MONTH(`end`) = @_MONTH
group by HOUR(`end`)
```
Above query returns only the h... | First, your query can be expressed in a simpler way as:
```
SELECT COUNT(*) AS totalCalls, HOUR(`end`) AS `Hour`
FROM callsDataTable c
INNER JOIN products p ON c.company = p.number
AND p.id IN (@_PRODUCTS)
AND YEAR(`end`) = @_YEAR AND MONTH(`end`) = @_MONTH
GROUP BY HOUR(`end`) AS `Hour`
ORDER BY `Hour` ASC
... | You need a `Hour` table and then do a `left Outer Join` with the `Hour_table`.
Which will ensure that all `hours` will be returned. If `hour` doesn't exists in `callsDataTable` then count will be `0`.
**Hours Table**
```
create table hours_table (hours int);
insert into hours_table values(0);
insert into hours_tabl... | Mysql: Group by Hour, 0 if no data | [
"",
"mysql",
"sql",
"time-series",
"aggregate-functions",
""
] |
I have two queries I've tested:
```
SELECT [FirstName], [LastName], [PreferredName], [DOB], [Sex], LastActivityDate,LoweredEmail, EmailConfirmed FROM [Patients] p
join AspNetUsers u on p.Id=u.PatientId
join AspNetUserRoles r on u.Id=r.UserId
WHERE (p.[ClinicId] = 1) and RoleId='16874754-779a-fbae-8caf-bbbb2344b7a6'
... | The second query is returning 1303 records:
```
SELECT AspNetUsers.id
FROM dbo.AspNetUsers INNER JOIN
dbo.AspNetUserRoles
ON AspNetUsers.Id = AspNetUserRoles.UserId
WHERE AspNetUsers.ClinicId = 1 and
AspNetUserRoles.RoleID='16874754-779a-fbae-8caf-bbbb2344b7a6'
```
The first query is returning 1301 r... | Have you tried SELECT DISTINCT?
Also try your checking query the other way (subquery to main query, main query to subquery) | two queries returning different result counts | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I wanted to change one of the fields to currency type during select
```
SELECT AdvertID,NumWords,WeeksRunning,0.5*NumWords*WeeksRunning AS [Cost]
FROM AdvertsTb
```
As you can see, the new field won't be in the format of $XX.00. So which operator must I use to change the type so that it is shown as a currency? | You'll need to cast it
```
SELECT AdvertID,NumWords,WeeksRunning,cast(0.5*NumWords*WeeksRunning as money) AS [Cost]
FROM AdvertsTb
``` | Just convert the `cost` to `varchar` and append `$` symbol.
```
SELECT AdvertID,NumWords,WeeksRunning,
"$" & CStr(0.5*NumWords*WeeksRunning) AS [Cost]
FROM AdvertsTb
``` | How to change the datatype of a field | [
"",
"sql",
"ms-access",
""
] |
I have the following data:
```
-------table_a-------
| id | data | value |
| 1 | 5 | 1 |
| 2 | 3 | 3 |
```
My desired output is to merge row 2 with row 1 so that where `id = 1`, data remains to `=5` but the values are added, so `1+3`.
```
-------table_a-------
| id | data | value |
| 1 | 5 | 4 ... | If this is the logic that you want:
```
UPDATE table_a
SET value = value + (SELECT a.value FROM table_a a WHERE a.id = 2)
WHERE id = 1;
DELETE FROM table_a WHERE id = 2;
```
The `update` is not going to work because you cannot reference the table being updated in the rest of the query. You can use a hack for... | Here is one way on how you can make an accumulative column by joining the table with itself.
I'm assuming the Id column is an identity column,
Hope this helps.
```
CREATE TABLE [dbo].[TestTable](
[id] [int] NULL,
[data] [int] NULL,
[value] [int] NULL
) ON [PRIMARY]
INSERT INTO [dbo].[TestTable]
... | Combining 2 rows in table | [
"",
"mysql",
"sql",
"merge",
""
] |
```
INSERT INTO table1
SELECT * FROM table2
WHERE NOT EXISTS
(SELECT 1 FROM table1
WHERE table2.id = table1.id)
```
What is the role of that `1` in the forth line of code? I want to make an incremental update of `table1` with records from `table2`. A friendly soul advised me to use the above query, which I... | Exists checks for the *presence* of rows in the sub-select, not for the data returned by those rows.
So we are only interested *if* there is a row or not.
But as you can't have a `select` without selecting something, you need to put an expression into the select list.
That could be *any* expression. The actual expre... | You can select whatever in the case of `EXISTS (sub-select`, the only thing that matters are if a row is found (EXISTS true), or no rows found (EXISTS false). | SQL insert into, where not exists (select 1... what this "1" stands for? | [
"",
"sql",
"insert",
"sql-server-2012",
""
] |
```
SELECT Region ,
flag ,
Name,
COUNT(ID) AS 'CountWithFlag'
FROM Table
GROUP BY flag
```
this query gives me the following results. I am grouping by flag and I am able to get the counts for English/non-English based on flag. I also want to display Total Counts of English and non-English a... | Another way would be something like this:
```
;
WITH agg1
AS (
SELECT region,
flag,
name,
COUNT(id) AS 'CountWithFlag'
FROM [dbo].[t2]
GROUP BY region,
flag... | try this
```
;
WITH cte
AS ( SELECT DISTINCT
Region ,
flag ,
Name ,
COUNT(ID) OVER ( PARTITION BY flag, Region, Name ) AS [CountWithFlag]
FROM [Table]
... | Aggregation and Total | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table:
```
ID | fish1 | fish2 | fish3 |
1 | shark | dolfy | whale |
2 | tuna | shark | dolfy |
3 | dolfy | shark | tuna |
4 | dolfy | tuna | shark |
```
and the result of he query is:
```
fish | count |
shark | 4 |
tuna | 3 |
dolfy | 4 |
whale | 1 |
```
Can someone give me a proper... | You need to create a normalized view on your de-normalized table:
```
select fish,
count(*)
from (
select fish1 as fish from the_table
union all
select fish2 from the_table
union all
select fish3 from the table
) t
group by fish
```
In general it's a bad idea to store your data like that (numbered c... | ```
select fish, count (id)
from
(
SELECT fish1 as fish, id from my_table
union all
SELECT fish2 as fish, id from my_table
union all
SELECT fish3 as fish, id from my_table
) A
group by fish
``` | Query to count items across multiple columns | [
"",
"sql",
"postgresql",
"aggregate-functions",
""
] |
I am pretty new to using MS SQL 2012 and I am trying to create a query that will:
1. Report the order id, the order date and the employee id that processed the order
2. report the maximum shipping cost among the orders processed by the same employee prior to that order
This is the code that I've come up with, but it ... | Step one is to read the order:
```
select o.employeeid, o.orderid, o.orderdate
from orders o
where o.orderid = @ParticularOrder;
```
That gives you everything you need to go out and get the previous orders from the same employee and join each one to the row you get from above.
```
select o.employeeid, o.orderid,... | It is unclear why you are using t3. From the question it doesn't sound like the employee's most recent order date is relevant at all, unless I am misunderstanding (which is absolutely possible).
I believe the issue lies in t2. You are grouping by orderdate, which will return the max freight for that date and employeei... | Getting max value before given date | [
"",
"sql",
"sql-server-2012",
""
] |
Here I am inserting values into two columns but now I want to both declared values which is created just now:
```
Declare @ClientCompanyId int, @PersonId int
INSERT INTO ClientCompany (CompanyName)
VALUES ('WebDunia')
SELECT @ClientCompanyId = SCOPE_IDENTITY()
INSERT INTO Person (ClientCompanyId, Company, Address... | Use another variable set, same as you use for `@ClientCompanyId`
```
Declare @ClientCompanyId int,
@PersonId int
INSERT INTO ClientCompany(CompanyName) VALUES ('Google')
SELECT @ClientCompanyId=SCOPE_IDENTITY()
Insert into Person (ClientCompanyId,Company,AddressLine1, AddressLine2,
... | why not just replicate what you do with `@ClientCompanyID` with @PersonID after the 2nd insert?
i.e. the line `SELECT SCOPE_IDENTITY() as PersonId` should read `SELECT @PersonID = SCOPE_IDENTITY()` Then both variables will have values set.
I don't know in which context this sql runs, but if you need both values out, ... | How can I return ScopeIdentity in a query of two Insert statements | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a table like
```
+------+-------+-------------------------------------+
| id | col2 | col3 |
+------+-------+-------------------------------------+
| 1 | 1 | 10 |
| 2 | 1 | 20 |
| 3 | 1 | 15 ... | You have to use this following simple sql query for your requirement.
```
SELECT TOP 1 ID
FROM table_name
Where col2 = 2
ORDER BY col3 DESC
```
You can use also `ROW_NUMBER()` function. It's another way for same result. | You could use `ROW_NUMBER`:
```
CREATE TABLE temp(
ID INT,
Col2 INT,
Col3 INT
)
INSERT INTO temp VALUES
(1, 1, 10), (2, 1, 20), (3, 1, 15),
(4, 2, 10), (5, 2, 20), (6, 2, 15),
(7, 2, 30);
SELECT
ID, Col3
FROM(
SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY col2 ORDER BY col3 DESC)
... | Get ID of a row having maximum value in other column | [
"",
"sql",
"sql-server",
""
] |
I have a table with a column that stores the date and time. I need to write a query to get only the date from that column,
```
SELECT CAST(CONVERT(VARCHAR, LoginTime, 101) AS datetime) FROM AuditTrail
```
But, when I run the query I am getting this error:
> The conversion of a varchar data type to a datetime data ty... | Try `ISDATE()` function in SQL Server. If 1, select valid date. If 0 selects invalid dates.
```
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
WHERE ISDATE(LoginTime) = 1
```
* [Click here](http://sqlfiddle.com/#!3/5b3cb/2) to view result
**EDIT :**
As per your update **i need to extra... | hope this may help you:
```
SELECT CAST(LoginTime AS DATE)
FROM AuditTrail
```
If you want to have some filters over this datetime or it's different parts, you can use built-in functions such as Year and Month | Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query | [
"",
"sql",
"sql-server",
"sql-server-2008",
"datetime",
""
] |
I have employee hours log data. Now I have to flag all the records where an employee logs the same hours for the same tasks on the consecutive work days (Sat/Sun weekend).
Let me explain my problem with following example
I have employee hour log table say EMP\_HOUR\_LOG:
```
ROW EMP_NO TASK DATE HOURS F... | Probably also rows 7 and 8 should have flag = 1.
This is the query, but I think the problem has to be handled during the insert:
```
update e set e.FLAG = 1
from [dbo].[EMP_HOUR_LOG] e
where exists
(
select * from [dbo].[EMP_HOUR_LOG] e1
where e1.[TASK] = e.[TASK]
and e1.[EMP_NO] = e.[EMP_NO]
and e1... | I am not sure if I understand it correctly:
Same Employee, same task, with same amount of hours input one day after another (consecutive - weekends excluded).
But your described logic will pick also rows: 7 and 8
```
7 1000 T3 2015-01-09 5 0
8 1000 T3 2015-01-12 5 0
```
It is same employee `1000` s... | SQL Server Cursor Loop Alternative | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
"cursors",
""
] |
I'm quite new to Oracle so I'm not totally familiar with the `ROWNUM` statement. I'm trying to get the latest 4 articles from my table. I'm getting 4 results but they are 2012 articles even though my date ordering is set to `DESC`. Any help would be great.
Oracle query:
```
SELECT bt.article_id, ba.*
FROM articles_t... | Just a wild guess, but order the result before rownum limit:
```
select t.* from
(
SELECT *
FROM articles_types bt
LEFT JOIN blog_articles ba
ON ba.article_id = bt.article_id
ORDER BY Published DESC
) T
WHERE ROWNUM <= 4
```
This worked, the issue was a duplicate column name | The `where` clause is evaluated before the `order by` clause. So what's happening here is that you're selecting the first four rows returned by the database (in completely arbitrary order), and then sorting them in descending order of `Published`.
One solution could be to move the `where` clause to an outer query:
``... | SELECT 4 latest rows from Oracle table with join | [
"",
"sql",
"oracle",
"date",
"join",
"rownum",
""
] |
I have two tables on a PostgreSQL database, contracts and payments. One contract has multiple payments done.
I'm having the two following models:
```
module.exports = function(sequelize, DataTypes) {
var contracts = sequelize.define('contracts', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true
... | This issue has been fixed on Sequelize 3.0.1, the primary key of the included models must be excluded with
```
attributes: []
```
and the aggregation must be done on the main model (infos in [this github issue](https://github.com/sequelize/sequelize/issues/3441)).
Thus for my use case, the code is the following
```... | Try
```
group: ['contracts.id', 'payments.id']
``` | Using group by and joins in sequelize | [
"",
"sql",
"node.js",
"postgresql",
"sequelize.js",
""
] |
How do I list all movies released between `2000` and `2010`?
```
SELECT title
FROM films
WHERE releaseYear > 2000 && < 2010
```
or do I have to use 'between'? I'm new to this and I'm trying to learn. I've looked for similar questions here on stackoverflow, but everyone seems to give a different answer. Are there di... | You can use the between clause like so:
```
Where ReleaseYear between 2000 and 2010
```
Or equivalent:
```
Where ReleaseYear >=2000 and ReleaseYear <= 2010
``` | You can use like this
```
SELECT title FROM films WHERE releaseYear between 2000 and 2010;
```
Tip: when you using "between" you should write smaller firstly. **between** **small value** and **bigger value** | SQL select query between two dates | [
"",
"sql",
"date",
"select",
"between",
""
] |
How do I create a function constraint for denormalized data?
```
-- graduation_class table
graduation_class_id | graduation_year_id
123 1
456 2
-- user table
user_id | graduation_class_id | graduation_year_id
555 123 1
556 ... | As mentioned by other answers, this schema is not ideal, but if you need to maintain data integrity in this schema before having the opportunity to clean things up, a function constraint will do this for you. First, we will create a function that takes in the `graduation_class_id` and `graduation_year_id` as parameters... | Instead of function create a `composite primary key` and a `foreign key` to fix your problem
Make the `graduation_class_id ,graduation_year_id` in `graduation_class` as composite `primary key`
```
ALTER TABLE graduation_class
ADD PRIMARY KEY (graduation_class_id ,graduation_year_id)
```
Now add `foreign key` in the ... | SQL Function Constraint for Denormalized Data | [
"",
"sql",
"sql-server",
"sql-function",
""
] |
Having a difficult time putting what I am trying to do into words so searching is also difficult.
Basically I am trying to look whether a certain value exists in a column, partitioned by group, and then propagate that value forward.
In this example I want to check whether a user has completed the tutorial and set a f... | You can filter SQL groups with the [`HAVING` clause](http://www.postgresql.org/docs/9.4/static/queries-table-expressions.html#QUERIES-GROUP). For example, you can group your table by users and their activity, and then filter it to contain only those that have completed the tutorial:
```
SELECT user FROM tbl
GROUP BY u... | I am not sure about the speed of this, but what about the following solution?
```
SELECT
user
,max(CASE
WHEN activity = "completed_tutorial" THEN 1
ELSE 0
END) AS completed_tutorial
FROM tbl
GROUP BY user
;
``` | Check whether value exists in column for each group | [
"",
"sql",
"postgresql",
""
] |
I have a select statement that is showing me all the data from table original every time it does not match the values on table real\_values.
So every time it does not match, instead of showing me which routes have the wrong values for capacity, I would like the query to update it with the correct values.
Here is a sh... | @DavidFaber's answer is how most people would do this. However, for this kind of query, I prefer to use `merge` over `update`:
```
MERGE INTO original o
USING real_values rv
ON (o.origin = rv.origin AND o.destination = rv.destination)
WHEN MATCHED THEN
UPDATE SET
o.capacity_wt = rv.capacity_wt, o... | The usual form of such an update query in Oracle is the following:
```
UPDATE table1 t1
SET t1.value = ( SELECT t2.value FROM table2 t2
WHERE t2.key = t1.key )
WHERE EXISTS ( SELECT 1 FROM table2 t2
WHERE t2.key = t1.key );
```
I'm confused though. You've tagged this question... | SQL - Update table values from values in another table | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I've come across some weird behavior that's preventing me from setting up a query in the way I'd like to. Would appreciate any ideas. If there's any information about the tables that would be helpful, please let me know. I looked through them and nothing jumped out at me that might cause this but nor did I know what I ... | Try with the `using` keyword which is designed for `join` on same column name
```
Select *
From
SCHEMA_A.TABLE_A a,
SCHEMA_B.TABLE_B b
Join
SCHEMA_C.TABLE_C USING(friend_id)
Join
SCHEMA_A.TABLE_D d using(group_id)
where b.group_cd = d.group_cd;
```
Also make sure that you execute the other query w... | I believe that you have run into the intricacy in SQL dealing with join scoping/precedence. Since I am not myself a database programmer, I can't really tell you why it works the way it does, but I do see some logic in the way the query parser is behaving.
In your first query, all the joins are cross joins. As a result... | Query throws ORA-00904 Invalid Identifier when using joins | [
"",
"sql",
"oracle",
""
] |
I'm getting an error as follows:
ORA-01858 - a non-numeric character was found where a numeric character was expected.
Although it isn't really accurate, I believe it's related to the date formatting in the following lines.
```
ELSIF par_report_eff_date_start IS NOT NULL AND par_report_eff_date_start = to_date(par_rep... | I notice that you have parameter par\_report\_eff\_date\_start, and a variable v\_report\_eff\_date\_start. You probably want to compare those in the following line:
ELSIF par\_report\_eff\_date\_start IS NOT NULL AND par\_report\_eff\_date\_start = to\_char(par\_report\_eff\_date\_start, 'fxdd/mm/yyyy')
But now you ... | You don't want to convert a `date` to a `date`. You want to convert it to a character string. So try:
```
to_char(par_report_eff_date_start, 'fxdd-mm-yyyy')
```
I'm not sure what the rest of the logic is supposed to be doing. But, you use `to_date()` to convert a value *to* a date and `to_char()` to convert a value t... | Oracle Date Format with input Parametres - PLSQL | [
"",
"sql",
"oracle",
"date",
"plsql",
""
] |
Let's say we have this table with columns `RowID` and `Call`:
```
RowID Call DesiredOut
1 A 0
2 A 0
3 B
4 A 1
5 A 0
6 A 0
7 B
8 B
9 A 2
10 A 0
```
I want to SQL query the last column `DesiredOut` as ... | You could use a query to find the previous `Call = A` row. Then, you could count the number of rows between that row and the current row:
```
select RowID
, `Call`
, (
select count(*)
from YourTable t2
where RowID < t1.RowID
and RowID > coalesce(
... | I would approach this by first finding the `rowid` of the previous "A" value. Then count the number of values in-between.
The following query implements this logic using correlated subqueries:
```
select t.*,
(case when t.call = 'A'
then (select count(*)
from table t3
... | SQL: Get running row delta for records | [
"",
"sql",
""
] |
I have a table with a list of timestamps and I want to calculate the duration between the timestamps
The Table list looks like this
```
MYTIME
2015-01-30-08.12.51.141000
2015-01-30-08.12.51.142000
2015-01-30-08.12.51.142000
2015-01-30-08.12.51.162000
2015-01-30-08.12.51.170000
2015-01-30-08.12.51.290000
```
what I wa... | Here is my DB2 solution:
I have a table with a single column filled with Tags and timestamps;
First I created a CTE to filter to records I wanted then I pulled out tags and timestamps and a newly created rank column.
Then with this CTE table I used the rank to join 1 to 2 then 2 to 3 etc. to get my duration.
\*Thanks t... | It's depend what SQL server are you using. Does it implemented Window Functions or not?
It would be operation between lines. Previous and Next time stamp difference.
In MS SQL 2008:
```
WITH AUXILIERY_TBL AS (
SELECT
A.[Time_Stamp]
,ROW_NUMBER() OVER (ORDER BY A.[Time_Stamp]) AS Ordr
FROM [Time... | How to calculate duration between a list of timestamps | [
"",
"sql",
"time",
"timestamp",
"duration",
""
] |
I want to query a giant table (SQL Server) for the latest version of a set of record e.g.
Table:
```
Id, key, Ver
1, A, 1
2, B, 1
3, A, 2
4, B, 2
5,B, 3
```
Result:
```
Id, Key, Ver
3, A, 2
5, B, 3
```
The join method mentioned in [here](https://stackoverflow.com/questions/9430743/selecting-most-recent-and-specifi... | Essentially, looping over a set of keys one at a time and performing a operation `n` times is a bad approach with any RDBMS. It prevents the query engine from optimizing and guarantees `n` seeks\scans of a table\index.
If you can express your query as a set based operation this will allow the query engine to fully opt... | Use a sub-select to find the max ver for a key:
```
select * from table t1
where ver = (select max(ver) from table
where key = t1.key)
``` | Best way to get the latest version of a specific list of records in SQL | [
"",
"sql",
"sql-server",
""
] |
```
select COUNT(analysed) from Results where analysed="True"
```
I want to display count of rows in which analysed value is true.
However, my query gives the error: "The multi-part identifier "Results.runId" could not be bound.".
This is the actual query:
```
select ((SELECT COUNT(*) AS 'Count'
FROM Results
... | Your problems are arising from improper joining of tables. You need information from both Runs and Results, but they aren't combined properly in your query. You have the right idea with a nested subquery, but it's in the wrong spot. You're also referencing the Analysed table in the outer where clause, but it hasn't bee... | I'd try the following query:
```
SELECT COUNT(*) AS 'Count'
FROM Results
WHERE Analysed = 'True'
```
This will count all of your rows where Analysed is `'True'`. This should work if the datatype of your `Analysed` column is either BIT (Boolean) or STRING(VARCHAR, NVARCHAR). | Count query giving wrong column name error | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I'm unsure the best route to take for this example:
A table that holds information for a job; salary, dates of employment etc. The field I am wondering how best to store is 'job\_title'.
* Job title is going to be used as part of an auto-complete field so
I'll be using a query to fetch results.
* The same job title... | Your option 1 is the best design choice. Create the two tables along these lines:
* jobs (job\_id PK, title\_id FK not null, start\_date, end\_date, ...)
* job\_titles (title\_id PK, title)
The PKs should have clustered indexes; jobs.title\_id and job\_titles should have nonclustered or secondary indexes; job\_titles... | Edited: after getting the clarify
A table like this is enough - just add the `job_title_id` column as foreign key in the main `member` table
> ```
> ---- "job_title" table ---- (store the job_title)
> 1. pk - job_title_id
> 2. unique - job_title_name <- index this
> ```
\_\_ original answer \_\_
You need to clari... | DB design for one-to-one single column table | [
"",
"mysql",
"sql",
"database",
""
] |
I have the following query:
```
SELECT
*,
(SELECT locked FROM forum_topics t WHERE t.id = topicid) as topiclocked,
forum_subtopics.locked as stlocked
FROM forum_subtopics
WHERE topicid = 1;
```
I would like to use the fields `topiclocked` and `stlocked` to create a third custom coloumn named `locked`. I t... | You can assign variables in the `select`-part, like this
```
SELECT
*,
@topiclocked:=(SELECT locked FROM forum_topics t WHERE t.id = topicid) as topiclocked,
@stlocked:=forum_subtopics.locked as stlocked,
(@topiclocked || @stlocked) as locked
FROM forum_subtopics
WHERE topicid = 1;
```
<http://sqlfidd... | You cannot use `alias name (topiclocked)` in the same `select` statement. Make the query as `sub-select` and do the concatenation in `outer query`. Try this.
```
SELECT *,
( topiclocked || stlocked ) AS locked
FROM (SELECT *,
(SELECT locked
FROM forum_topics t
... | MySQL SELECT use 2 newly created "coloumns" in a third | [
"",
"mysql",
"sql",
""
] |
This is quite a mouthfull for me.
One of my challenges is that I don't know how to formulate the question - which is obvious by the title.
I'll try to illustrate my problem:
I have a table, A:
```
ID LocationID
11 185
12 185
13 206
```
And a table B:
```
ID AID Position Value
1 11 1 ... | You can do this with `GROUP BY` and `HAVING`:
```
SELECT A.ID
FROM A
INNER JOIN B ON (A.ID = B.AID)
GROUP BY A.ID
HAVING MAX(CASE WHEN A.LocationID = 185 THEN 1 END) = 1
AND MAX(CASE WHEN B.Position = 1 AND B.Value = 4 THEN 1 END) = 1
AND MAX(CASE WHEN B.Position = 3 AND B.Value = 5 THEN 1 END) = 1
```
Dem... | ```
SELECT DISTINCT A.ID
FROM A
WHERE A.ID IN(
SELECT ID
FROM B
WHERE (B.Position = 1 AND B.Value = 4) OR
(B.Position = 3 AND B.Value = 5)
)
```
If I understand you correctly.
SELECT DISTINCT A.ID
FROM A
INNER JOIN B ON (A.ID = B.AID)
WHERE
A.LocationID = 185 AND
(B.Position = 1 AND B.Value = 4) OR
(B.Po... | T-SQL - Find distinct values in table only if joined rows satisfy a list of criterias | [
"",
"sql",
"sql-server",
"join",
"set-theory",
""
] |
I have 2 tables :
```
interests (storing the interest ID and name)
person_interests(storing the person_id and interest_id)
```
How do I select all the interests that a particular person has not selected?
I have tried the following SQL Query and am still not getting the desired result
```
SELECT *
FROM interests ... | Use `NOT EXISTS`
```
SELECT *
FROM interests
WHERE NOT EXISTS (
SELECT person_interests.interest_id
FROM person_interests
WHERE person_id = 66
AND interests.id = person_interests.interest_id
)
``` | ```
SELECT * from interests
WHERE interest_id NOT IN
(SELECT interest_id FROM person_interests WHERE person_id=66)
``` | Opposite of UNION SQL Query | [
"",
"sql",
"postgresql",
""
] |
I'm a bit confused by the stored procedure syntax in Oracle.
I started with a simple:
```
select * from test_table;
```
It works, then I put it in a proc:
```
CREATE OR REPLACE PROCEDURE example
IS
BEGIN
select * from test_table;
END;
```
Doesn't work. Expected "INTO" is the error message I get. Now, I've seen ... | T-SQL and PL/SQL are completely different languages. In particular, for PL/SQL you have to select the result into some variable or cursor. Depending on what you plan to do with the record data - process in the procedure - or return to the caller, will drive what you have to do.
In your example, if you want to return t... | Hello and welcome to SO.
I assume the full error you're seeing would be `PLS-00428: an INTO clause is expected in this SELECT statement` and it is correct, you must have an `INTO` statement in a stored procedure.
I recommend [this](http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/selectinto_statement.htm#LNPLS... | select stored proc plsql | [
"",
"sql",
"database",
"oracle",
"stored-procedures",
"plsql",
""
] |
IS there a way to run this across every column in a table:
```
UPDATE dbo.stage_a
SET Statement_Name= NULL
WHERE Statement_Name='""';
```
I am trying to tidy up after a data import. | `Dynamic query` plus `Information_schema.columns`. Try this.
```
DECLARE @cols NVARCHAR(max)='UPDATE dbo.stage_a set '
SELECT @cols += COLUMN_NAME + '=case when ' + COLUMN_NAME
+ ' = '""' then null else '+COLUMN_NAME+' end,'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'stage_a'
AND TA... | ```
UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';
```
Like this example you should specify all coloumns.(separated by commas)
If you want to replace all coloumns with NULL why don't you delete the rows:
```
DELETE FROM Customers
WHERE CustomerName='Alfred... | Global Update (All Rows) On One SQL Table With The Same Criteria | [
"",
"sql",
"sql-server-2008",
""
] |
I have 2 queries do the same job:
```
SELECT * FROM student_info
INNER JOIN class
ON student_info.id = class.studentId
WHERE student_info.name = 'Ken'
SELECT * FROM (SELECT * FROM student_info WHERE name = 'Ken') studInfo
INNER JOIN class
ON student_info.id = class.studentId
```
Which one is faster? I guess the ... | In the latest versions of Oracle, the **optimizer** is smart enough to do its job. So it won't matter and both of your queries would be internally **optimized** to do the task efficiently. Optimizer might do a **query re-write** and opt an **efficient execution plan**.
Let's understand this with a small example of EMP... | You'd need to show us the query plans and the execution statistics to be certain. That said, assuming `name` is indexed and statistics are reasonably accurate, I'd be shocked if the two queries didn't generate the same plan (and, thus, the same performance). With either query, Oracle is free to evaluate the predicate b... | Comparing two join queries in Oracle | [
"",
"sql",
"oracle",
"join",
""
] |
I have to run a query to a table to get sums per a specific field value.
```
rechargedate originid
------------------------
2015-02-02 3
2015-02-02 3
2015-02-02 1
2015-02-02 1
2015-02-02 3
2015-02-02 2
2015-02-01 2
2015-02-01 3
2015-02-01 1
2015-02-01 1
2015-02-01 ... | You can use conditional aggregation:
```
CREATE TABLE #temp(
RechargeDate DATE,
OriginID INT
)
INSERT INTO #temp VALUES
('2015-02-02', 3),('2015-02-02', 3),('2015-02-02', 1),
('2015-02-02', 1),('2015-02-02', 3),('2015-02-02', 2),
('2015-02-01', 2),('2015-02-01', 3),('2015-02-01', 1),
('2015-02-01', 1... | Use `PIVOT`. Check [this](https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx) to learn `PIVIOT` in `SQL SERVER.`
```
SELECT rechargedate,
[1] AS orig1,
[2] AS orig2,
[3] AS orig3
FROM #TEST
PIVOT(COUNT(originid) FOR originid IN([1],[2],[3])) AS Piv
ORDER BY rechargedate DESC
``... | How to summarize by row and specific value of a field | [
"",
"sql",
"sql-server",
""
] |
In Oracle [documentation](http://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#i22289) it is mentioned that
> NUMBER (precision, scale)
>
> If a precision is not specified, the column stores values as given. If
> no scale is specified, the scale is zero.
But `NUMBER` (without precision and scale) is als... | The default of scale is not zero, which has no value in it. Hence it can accept any value between `-84 to 127`. If you limit it to zero then it will not accept any presicion even the value contains the scale value
```
create table aaaaa
(
sno number(*,0),
sno1 number
);
```
The `user_tab_columns` will give you the va... | I think the sentence in the documentation
> If a precision is not specified, the column stores values as given. If no scale is specified, the scale is zero.
is a bit confusing. The scale is zero *if a precision is specified and a scale is not specified*. So, for example, `NUMBER(19)` is equivalent to `NUMBER(19,0)`. ... | Is "NUMBER" and "NUMBER(*,0)" the same in Oracle? | [
"",
"sql",
"oracle",
"types",
"oracle11g",
"sqldatatypes",
""
] |
Iam trying to get the results from two columns with the same type into single column for example
```
table
id secId
1 2
3 1
5 1
1 4
```
i want to retrive them like that where id or secId = 1
```
id
2
3
4
5
```
i have tried inner join but it gives me 2 columns with data redundan... | You could use a `union` to get that
```
select id from yourTable where secId = 1
union
select secId from yourTable where id = 1
```
Use `union all` if you don't like the way `union` also does a `distinct` | You don't need any `Join` for that, this simple query would do it
```
select if(id=1, secId, id)
from yourTable
where id = 1 or secId = 1;
```
You select all data that have `id` or `secId` equal to `1` then, depending on which of both is equal to `1` you display `secId` or `id`.
Assuming here only one of both va... | how to join two columns into single column from the same table | [
"",
"mysql",
"sql",
"join",
"inner-join",
""
] |
I am trying to select all rows that has either the same username OR email as any users EXCEPT the one with ID 7.
But now it returns the row that actually has the ID 7. I was thinking that perhaps you can do some grouping of your SQL to solve this?
Can anyone tell me whats wrong?
This is my SQL that I am trying with ... | Put parenthesis around OR:
```
SELECT user_id
FROM user
WHERE (username = "my_username" OR email = "my@email.com")
AND user_id != 7
```
Without them, `AND` will be evaluated prior to `OR` because it has [higher priority](http://dev.mysql.com/dhttp://dev.mysql.com/doc/refman/5.0/en/operator-precedence.htmloc/refman/5.... | I think you made a general mistake here. You used OR and AND both in where clause without putting (). Following example should work i guess :
```
SELECT user_id FROM user
WHERE (username = "my_username" OR email = "my@email.com") AND user_id != 7
```
You can take a look [operator precedence in my sql](http://dev.mys... | Select all rows that has either A=B OR C=D EXCEPT where ID=foo in MySQL | [
"",
"mysql",
"sql",
""
] |
I have a table
* items: `id, userid, item_name, item_description`
I want to update a row and used the following sql statement for it.
```
$updateQuery = "UPDATE items SET item_name = '$item_name',
item_desc = '$item_desc' WHERE userid = '$userid'
AND item_name = '$old_name'";
```
But it fails. Is it because I used... | I think I see the problem
```
item_desc = '$item_desc'
```
"4 columns id, userid, item\_name, **item\_description.**"
Change your query to
```
$updateQuery = "UPDATE items SET item_name = '$item_name', item_description = '$item_desc' WHERE userid = '$userid' AND item_name = '$old_name'";
``` | you not update item\_name because you used it in where clause
or
you can echo this string and run in database terminal to verify.
Try :
```
$updateQuery = "UPDATE items SET item_name = '" . $item_name . "', item_desc = '" . $item_desc . "' WHERE userid = " . $userid . " AND item_name = '" . $old_name . "';"
``` | Error in updating database row in MYSQL | [
"",
"mysql",
"sql",
""
] |
I am trying to insert records from another table into a table in Access using sql. I have pasted the statement below. I want to insert the records that exist in ImportMetricsIDs01262015 but not in ShouldImportMetricsIDs. It runs perfectly without any errors but it won't insert anything even when I physically add a new ... | You need a correlation clause. The subquery just checks whether or not the table is empty. Something like:
```
INSERT INTO ShouldImportMetricsIDsTable( [Formulary ID], [Market Segment] )
SELECT im.[Formulary ID], im.[Market Segment]
FROM ImportMetricsIDs01262015 as im
WHERE NOT EXISTS (SELECT 1
... | You need to correlate your `NOT Exist` query with the `ImportMetricsIDs01262015` table
This code is on the assumption that FormularyID is the key in both the tables.
```
INSERT INTO ShouldImportMetricsIDsTable (
[Formulary ID]
,[Market Segment]
)
SELECT ImportMetricsIDs01262015.[Formulary ID]
,ImportM... | Insert INTO NOT EXISTS SQL access | [
"",
"sql",
"vba",
"ms-access",
"insert",
""
] |
Sorry for that title, I don't know how to describe my problem in one sentence.
I have Table like this:
```
event | thema
-------------
1 1
1 2
2 1
2 2
2 3
3 1
3 2
3 3
3 4
4 1
4 2
4 3
```
What I want are the event IDs where the thema is exaclty 1... | This type of query is a "set-within-sets" query (your are looking for sets of "thema" for each event). The most general approach is aggregation using a `having` clause. This might be the shortest way to write the query using standard SQL:
```
select event
from table t
group by event
having count(distinct (case when th... | Group by the `event` and take only those having at least one `thema` 1 and 2 and 3 and not any other
```
SELECT event
from your_table
group by event
having sum(case when thema = 1 then 1 else 0 end) > 0
and sum(case when thema = 2 then 1 else 0 end) > 0
and sum(case when thema = 3 then 1 else 0 end) > 0
and sum(case ... | SQL get all IDs where Sub-IDs are exactly specified without getting other IDs where some Sub-ID's are not present | [
"",
"sql",
"sql-server",
""
] |
I need to create this table function. The function needs to return single words from passed parameters like: hello, hhuu, value
The table function should return:
```
hello,
hhuu,
value
```
But I am always getting some errors, please could you help me? | you can write as:
```
DECLARE @input_char VARCHAR(255)
SET @input_char = 'hello, hhuu, value'
;WITH cte AS (
SELECT
CAST('<r>' + REPLACE(@input_char, ' ', '</r><r>') + '</r>' AS XML) AS input_char
)
SELECT
rtrim( LTRIM (xTable.xColumn.value('.', 'VARCHAR(MAX)')) ) AS input_char
FROM cte
C... | Please give a look at this article:
<http://www.codeproject.com/Tips/625872/Convert-a-CSV-delimited-string-to-table-column-in>
and you could use ' ' (space) as delimiter.
```
SELECT * FROM dbo.CSVtoTable('hello, hhuu, value', ' ')
``` | MSSQL - Create table function, return substring | [
"",
"sql",
"sql-server",
"t-sql",
"stored-procedures",
""
] |
I have 2 posts in my table that can be published on homepage. First has 3 comments and the other has no comments. Query below gives 1 result row but I want 2 result rows.
Expected result of the query
1. fetch requested rows from blog table
2. fetch COUNT of comments for the related post id. IF no comment is available... | A `left join` returns blogs even though they have no matching comment:
```
select b.id
, b.body
, count(c.commentid)
from blog b
left join
comments c
on b.id = c.blogid
where b.status = 'publish'
group by
b.id
, b.body
order by
b.id desc
``` | At a first glance, you may need a left join:.
Edit: Confirmed. Have a look at this: <http://sqlfiddle.com/#!2/1475ab/1>
```
$query = 'SELECT
b.id,
b.body,
COUNT(c.comment)
FROM blog b
left join comments c
on b.id = c.postid
WHERE blog.status="publish"
group by b.id
ORDER BY b.id DESC';
``` | MySQL query simultaneously combined result from 2 tables (fetch if count() is zero also) | [
"",
"mysql",
"sql",
""
] |
I have a table that has some columns containing strings ,Let's say `nvarchar`. Now, the user passes a string to a function that searches for this string in its assigned column. I want to check if that string is present in the database but the problem is it does not necessarily have to be a 100% match.
Let's say for exa... | You can do it this way:
```
SELECT Name, LEN(Name) AS Equals, (LEN('Johnathon') - LEN(Name)) AS NotEquals
FROM TableName
WHERE 'Johnathon' LIKE '%' +Name +'%'
```
Or if you want to compare both ways then:
```
DECLARE @parameter NVARCHAR(MAX) = N'Johnathon'
SELECT Name,
CASE WHEN LEN(Name) > LEN(@parameter) THEN LE... | The Levenshtein distance mentioned by @DeadlyJesus might suit you, but an alternative would be just to count matching characaters from the start of the 2 strings. A simple user defined function could do this.
```
create function dbo.MatchStart(@input1 nvarchar(100), @input2 nvarchar(100)) returns int as
begin
dec... | Matching strings in TSQL | [
"",
"sql",
"ssms",
""
] |
I have a table **A** which has primary key column **a** and it is a foreign key to **B** table (Table B has primary key b and column a). Table B also has a primary key b which foreign key to C table and so on.
It won't allow me to delete a row from table A because its dependent on table B and table B is dependent on t... | You Can Use Cascade `Cascading Referential Integrity Constraints`
**Update:**
you should enable Cascading Referential Integrity Constraints of Table A (PK) from Table B where ID of A is foreign Key and similarly of PK of Table B From Table C Where ID of B is foreign Key
 and [this](http://www.databaseprimer.com/pages/relationship_1to1/)
For an example, below are some statements ... | > The relationship between customer and order tables are one to many, that is because one customer can make many orders.
This should better read
* a customer can place **many** orders
* an order belongs to **one** customer
So it is a **one to many** relationship between the tables.
> customer and contactData tables... | Dongle. You are making a mistake of looking at the subject symmetrically. Relationship is considered to be one-directional, that's why you felt confused.
Let's take for example this *Customer <-> Order* relation. Like you observed, *customer -> order* is something completely different than *order -> customer*. They ar... | Confused on SQL Relationships | [
"",
"sql",
"relational-database",
""
] |
I have table holding a hierarchical structure so basically it has 3 columns as :

What I want is to select from this table by a range of ID's for example :
```
Id IN (1,4,8,18)
```
which results to :

INSERT INTO @t
VALUES ( 1, NULL ),
( 2, 1 ),
( 3, 2 ),
( 4, 3 ),
( 6, NULL ),
( 7, 6 ),
( 8, 7 ),
( 9, 8 ),
( 10, 9 ),
( 11, 10 ),
( 13, NULL ),
( 14, 13 ),
... | Split your task into two steps
1. Find top most parent
2. Find all decedents
```
WITH ToTopParent AS
(
SELECT Id, ParentId
FROM yourTable
WHERE Id IN (1,4,8,18)
UNION ALL
SELECT T.Id, T.ParentId
FROM ToTopParent TTP
JOIN yourTable T ON TTP.ParentId = T.Id
... | Select from a hierarchy based on a range of ID's | [
"",
"sql",
"sql-server",
"t-sql",
"tree",
"hierarchy",
""
] |
I have a TABLE (Classes\_Teachers) with 3 columns (classID - INT, teacherID INT , isActive BOOLEAN).
I read the contents of a new file and create a table (StudentsTemp) with the same columns but with the latest Data and want to "merge" the two.
I can do this easily using EXCEPT AND JOIN, however this will delete any ... | First, insert new `teacherID` and `classID` combination. Then update rows from `Students` table.
```
CREATE TABLE #Students(
ClassID INT,
TeachedID INT,
isActive BIT
)
CREATE TABLE #StudentsTemp(
ClassID INT,
TeachedID INT,
isActive BIT
)
INSERT INTO #Students VALUES
(1, 2, 1)... | Have you tried using a Merge statement?
<https://msdn.microsoft.com/en-us/library/bb510625.aspx> | Update one table with the results from another | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Lets say i have a value like this:
```
Z00056ABC00044
```
I would like to know what the values are BEFORE ABC
So my query should return only:
```
Z00056
```
I have tried to create a function:
```
if CHARINDEX('ABC',@mainString) > 0
begin
--do something
end
```
But i am unsure how to grab the value before ABC | Try this:-
```
SELECT SUBSTRING('Z00056ABC00044', 1, CHARINDEX('ABC', 'Z00056ABC00044') -1)
``` | Try this:
```
SELECT LEFT(@MyValue, (LEN(@MyValue) - CHARINDEX('ABC', @MyValue) - 1))
``` | Return section of a string | [
"",
"sql",
"sql-server-2008",
"t-sql",
""
] |
I've got a table with 3 columns: `name`, `lastname` and `date`.
For example:
```
Name Lastname Date
Ab Ab 2008-07-01
Ab Ab 2006-06-23
Kb Kb 2008-07-01
Kb Kb 2007-06-03
```
I need to find the names of those who are assigned to `2008-07` and not to `2006-06`. So for this example the out... | I think you want a `group by` and a `having` clause, because you are looking for multiple rows:
```
select Name, Lastname
from MyTable
group by Name, LastName
having
sum(case when YEAR(date) = 2008 AND MONTH(date) = 7 then 1 else 0 end) > 0 and
sum(case when YEAR(date) = 2006 AND MONTH(date) = 6 then 1 else ... | ```
SELECT
t.*
FROM (
SELECT
Name,
LastName
FROM #Temp
GROUP BY Name, LastName
HAVING
SUM(CASE WHEN YEAR([Date]) = 2008 AND MONTH([Date]) = 7 THEN 1 ELSE 0 END) = 1
AND SUM(CASE WHEN YEAR([Date]) = 2006 AND MONTH([Date]) = 6 THEN 1 ELSE 0 END) = 0
)x
INNER JOIN #Temp ... | Two "where" statements with one table doesn't work without subqueries | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
"where-clause",
""
] |
I've had a search around and have seen quite a few questions about selecting distinct values, but none of them seem close enough to my query to be able to help. This is the scenario
```
ID Product_ID Product_type
123 56789 A
123 78901 B
456 12345 A
789 45612 B
```
The SQL I need wo... | One way via a list of IDs appearing once:
```
select * from T where Product_type = 'B' and id in (
select id from T
group by id
having count(id) = 1)
``` | Soltuion 1: Use a sub-query to count id's.
```
select * from table t1
where Product_type = 'B'
and (select count(*) from table
where id = t1.id) = 1
``` | SQL - Selecting unique values from one column then filtering based on another | [
"",
"sql",
""
] |
I have a database that I'm trying to query from Access with ODBC. The table I need to read from has 304 columns, and I can only see the first 255 in the Query Builder. I've read elsewhere that the solution is to write an SQL query by hand rather than relying on the Builder, so I tried this query:
```
SELECT [Field1], ... | You have encountered a limitation of ODBC linked tables in Access, and a query like
```
SELECT ... FROM [ODBC;...].[tableName];
```
is really just a way of creating a temporary ODBC linked table "on the fly".
When Access goes to create an ODBC linked table it queries the remote database to get the column information... | Thanks Gord! That solves the problem of update large tables from within Access.
If anyone is interested, I've created a view inside sql server, selecting only the fields I wanted, then I link it inside Access.
Now, any update made in this link, reflects to the original table. So it's easy to do this running querys. | Access ODBC can't pull from SQL table with more than 255 columns | [
"",
"sql",
"ms-access",
"odbc",
"ms-access-2013",
""
] |
I'm trying to sum up all transactions for each day in my database.
```
SELECT DISTINCT
SUM(Balance) OVER (partition by Date) AS account_total,
Date
FROM tbl_FundData
ORDER BY Date;
```
The problem with the output is if a transaction is completed at a different time it becomes its own unique sum instead of... | Seems yo use DateTime as column data type so cast it as DATE :
```
SELECT DISTINCT SUM(Balance) OVER (partition by CAST([Date] AS DATE)) AS account_total, CAST([Date] AS DATE)
FROM tbl_FundData
ORDER BY CAST([Date] AS DATE);
```
Also you'd better use Group By in this case as :
```
SELECT SUM(Balance) AS account_tot... | ```
SELECT DISTINCT
SUM(Balance) OVER (partition by convert(varchar, Date, 103)) AS account_total,
convert(varchar, Date, 103) Date
FROM tbl_FundData
ORDER BY convert(varchar,Date,103)
``` | Summing a column by all transactions in a day | [
"",
"sql",
"sql-server-2008",
""
] |
I have a list of cust\_id and timestamps for an activity. I would like to add a column called "activity\_order" which would give an order to each cust\_id, which "1" being assigned to the max timestamp
```
cust_id | time_stamp
________ __________
a1 2015-01-31 10:48:43
a1 2015-01-31 12:48:46
a1 ... | ```
SELECT cust_id
, time_stamp
, RANK () OVER(PARTITION BY cust_id ORDER BY time_stamp DESC) as activity_order
FROM activity
ORDER BY cust_id ASC, activity_order DESC
```
working example: <http://sqlfiddle.com/#!6/b6d85/3>
for more info: <http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions123.htm> | Try assuming MS SQL
```
Update B
Set Activity_Order = RN
From
(select CustID, [Time_stamp], Row_Number() Over(Partition By CustID Order By [Time_stamp] desc) as RN
From Activity) A
inner join Activity B on A.CustID = B.CustID and A.[Time_stamp] = B.[Timestamp]
``` | SQL Order by Timestamp and Assign Numeric Value | [
"",
"sql",
"hive",
"hql",
""
] |
```
class Category < ActiveRecord::Base
has_many :articles
end
class Article < ActiveRecord::Base
belongs_to :category
has_many :comments
has_many :tags
end
```
`Category.joins(:articles)` in rails equivalently
```
SELECT categories.* FROM categories
INNER JOIN articles ON articles.category_id = categories... | ```
Category.select('*').joins(:articles)
```
or
```
categoyes = Category.select('*').includes(:articles)
```
and
```
categoyes.each do |category|
puts category.articles
end
``` | Try to use `select` method
```
categories = Category.select('*').joins(:articles)
categories.first.some_column_from_articles
``` | All columns in join in ruby on rails | [
"",
"sql",
"ruby-on-rails",
"join",
""
] |
I have a table in which i have START\_DATE column which is DATE datatype. I want to get all the SUBSCRIPTION\_ID which is older than the last 30 min from the current datetime.
Here is my query:
```
select WF.SUBSCRIPTION_ID,WF.START_DATE
from WF_WORKFLOW
where WF.NAME='SIGNUP_MOBILE_PRE_PAID'
and WF.STATUS_ID=0... | You can amend the `where` clause with another condition:
```
start_date < sysdate - 30 / (24 * 60)
```
Oracle interprets a date as a number of days value. So, 30 minutes is `30 / (24 * 60)`. | Take a look at [INTERVAL](http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements003.htm#i38598)
So this might work,
```
select WF.SUBSCRIPTION_ID,WF.START_DATE
from WF_WORKFLOW
where WF.NAME='SIGNUP_MOBILE_PRE_PAID'
and WF.STATUS_ID=0 and WF.START_DATE < sysdate - INTERVAL '30' minute(1)
``` | Calculate DateTime difference in query | [
"",
"sql",
"oracle",
"datetime",
""
] |
I have 4 tables (as shown in the picture), I want to select Invoice, Client for which invoice is issued, And all the items for which the invoice is issued.
I cannot figure out how? How should I apply joins, or should i use sub queries?
Please helpe me, I am really struck.
)
INSERT INTO @Example (ID, Item)
SELECT 1, 'TextLineA' UNION ALL
SELECT 1, 'TextLineB' UNION ALL
SELECT 2, 'TextLineA' UNION ALL
SELECT 3, 'TextLineA' UNION ALL
SELECT 3, 'TextLineB' UNION ALL
SELECT 3, 'TextLineC'
select ID... | Use `Pivot`
```
SELECT id,
CASE WHEN [TextLineA] IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END [TextLineA],
CASE WHEN [TextLineB] IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END [TextLineB]
FROM Yourtable
PIVOT (Max(Item)
FOR item IN ([TextLineA],[TextLineB])) piv
``` | SQL rows to columns (Pivot with just bit values) | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm trying to convert `string` column to `date` in Oracle SQL.
Here is my an example of value from the data:
```
'03/12/14 11:00:00'
```
Here is my query:
```
select to_date(A,'DD/MM/YY HH24:MI:SS')
from MyTable
```
Here is an example of the output:
```
03-DEC-14
```
Why my query return only the date but not the... | Assuming you are using SQL\*Plus (or SQL Developer) the default NLS\_DATE\_FORMAT is applied when a `DATE` value is *displayed*. To verify your current format you can run:
```
select value
from nls_session_parameters
where parameter = 'NLS_DATE_FORMAT';
```
To adjust this, run:
```
alter session set nls_date_forma... | You are trying to **DISPLAY** the datetime value. Use **TO\_CHAR** along with proper **FORMAT MODEL**.
For example,
`select to_char(sysdate, 'mm/dd/yyyy hh24:mi:ss') from dual;`
A **DATE** consists of both date and time portions. You just need to make sure you use appropriate format model to display it. Else, you en... | Convert string to date in Oracle SQL | [
"",
"sql",
"oracle",
"to-date",
""
] |
I am doing a data migration between two tables (splitting out a related table). The existing table is `reminders`, and it has a `start` column and a newly-added `dateset_id` column pointing to a new `dateset` table, which also has a `start` column. For every row in `reminders`, I want to `INSERT` a new row in `dateset`... | There are several ways to solve the problem.
**1. temporarily add a column**
As others mentioned, the straight-forward way is to temporarily add a column `reminder_id` to the `dateset`. Populate it with original `IDs` from `reminder` table. Use it to join `reminder` with the `dateset` table. Drop the temporary column... | ## Update based on changes in Postgres:
Using INSERT RETURNING in subqueries is, according to the documentation, supported, for Postgres versions 9.1 and after. The hypothetical DML subquery in the original answer should work for Postgres >= 9.1:
```
UPDATE reminder SET dateset_id = (
INSERT INTO dateset (start)
... | PostgreSQL - insert rows based on select from another table, and update an FK in that table with the newly inserted rows | [
"",
"sql",
"postgresql",
""
] |
I have a query that is already calculating a running total for new clients and clients that have left. However if there are no new clients or no clients have left when I try to plot this on a graph I get blank spaces.
How can I get the previous years figures if a year is null?
```
select x.Year
, case when x.... | Maybe the lag function (msdn.microsoft.com/en-us/library/hh231256.aspx) can help you? | This was my amended code, I changed 2 lines in the select to use the lag function, I used the link in my answer to get this working.
```
select x.Year
, case when x.TotalClients is null then 0 else x.TotalClients end as 'TotalNewClients'
, x.RunningTotal
, case when x.RunningTotal is null then... | sql get previous row value for a running total | [
"",
"sql",
"sql-server",
""
] |
I want to do search in my app. Here is a general look of my query
```
SELECT * FROM My_Table WHERE Col1 OR col or Col3 LIKE "String";
```
My question is what is the correct syntax for that query.
Thanks. | The correct syntax looks like:
```
SELECT * FROM My_Table WHERE Col1 LIKE "%String%" OR col LIKE "%String%" or Col3 LIKE "%String%";
``` | ```
SELECT * FROM My_Table
WHERE LOWER(Col1) LIKE '%string%'
OR LOWER(Col2) LIKE '%string%'
OR LOWER(Col3) LIKE '%string%';
```
It is usually recommended to keep the search non case-sensitive. Here is the syntax for it. | Mention more than one coloumn in where cause | [
"",
"sql",
"where-clause",
"sql-like",
""
] |
I'm struggling with this piece of code:
```
INSERT INTO Bier(Bier, BrowuerID, TypeID, GistingID, KleurID, Alcohol)
SELECT bb.Naam, b.BrouwerID, t.TypeID, g.GistingID, k.KleurID, bb.Alcoholperc
FROM BELGISCHBIER AS bb JOIN Brouwer AS b JOIN Type AS t JOIN Gisting AS g JOIN Kleur AS k
```
Can someone tell why this won'... | You have used `JOINS` without the mandatory `ON` clause which determines on what columns the tables should be joined:
```
INSERT INTO bier
(
bier,
browuerid,
typeid,
gistingid,
kleu... | with `JOIN`, SQL understand `INNER JOIN`. So is mandatory use of `ON` clause.
Only if you use `CROSS JOIN` you can don't write `ON` clause.
So, add `ON` clause in your `JOIN` command. | MSSQL Select more Tables to INSERT | [
"",
"sql",
"sql-server",
"insert",
""
] |
Oracle SQL update from one Table to another table throws syntax error for following simple update query.
```
UPDATE Sales_Import SI
SET AccountNumber = RAN.AccountNumber
FROM RetrieveAccountNumber RAN
WHERE RAN.LeadID = SI.LeadID;
```
**Error:**
```
Error starting at line 1 in command:
Error at Command Line:2 Column... | > and whatever i tried is this ANSI standard query ?
No. Oracle Oracle doesn't support join in update statement.
In Oracle you could do it in two ways -
\*\*Merge statement \*\*
with only **update clause** in merge statement
```
MERGE INTO sales_import s
USING (SELECT *
FROM retrieveaccountnumber) u
... | I will write your sql like this:
```
UPDATE Sales_Import SI
SET AccountNumber = (Select RAN.AccountNumber
FROM RetrieveAccountNumber RAN
WHERE RAN.LeadID = SI.LeadID);
``` | Oracle SQL update from one Table to another table throws syntax error | [
"",
"sql",
"oracle",
""
] |
I have a date format like
```
'2003-11-27 00:00:00.000'
```
How can I convert it into `YYYYMMDD` like 20031127 WITH SQL SERVER ? | It depends of how your date is declared.
```
DECLARE @date datetime = '2003-11-27T00:00:00.000' -- datetime
DECLARE @date2 char(23) = '2003-11-27 00:00:00.000' -- char(23)
SELECT
convert(char(8), @date, 112) datetimeconvert,
convert(char(8), convert(datetime, @date2, 121), 112) charconvert
```
Result:
```
dat... | To convert the date as per ISO standard you can write as:
```
SELECT CONVERT (VARCHAR(8), GETDATE(),112) as [YYYYMMDD]
``` | Convert format of date | [
"",
"sql",
"sql-server",
""
] |
i am working with SQL Server 2012, i need to remove a particular string data from column values this string has saved multiple times for a user into the column.
I need to write the stored procedure for it. My table structure is like following.
```
Id UserId ColumnNeedUpdate Address
1 2565 ... | ```
UPDATE MyTable SET ColumnNeedUpdate =
REPLACE(ColumnNeedUpdate, 'l:\xyz\sfd\', '')
WHERE UserId = 2565
```
**Disclaimer:** This code changes the data in your table. Use at your own discretion. | It should work even with a non static "l:\xyz\sfd\" string :
```
UPDATE MyTable SET ColumnNeedUpdate =
REVERSE(SUBSTRING(REVERSE(ColumnNeedUpdate), 0,
CHARINDEX('\', REVERSE(ColumnNeedUpdate)) - 1))
WHERE UserId = 2565
``` | how to replace string values of column values by SQL Stored Procedure | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I need to use sql query to DB from soap every day automatically.
Query to DB has current date.
So, I do following:
1) I set current date to properties with groovy:
```
def dateTime= new Date()
setProperty.setPropertyValue('currDate', String.format("%tF", dateTime, new Date()))
```
2) in jdbc request I make corr... | You could use SQL to figure out the date, and then it will always be in the correct format:
```
select * ...
where SENDDATE = now()
``` | First of all, make sure your mysql field data type is relevant (it should be 'date' not time(), text, varchar etc.)
Regarding the groovy formatting way, Here is how:
```
import groovy.time.*
def dateTime= new Date().format('yyyy/MM/dd')
testRunner.testCase.testSteps["Properties"].setPropertyValue('currDate',dateTime... | soapui jdbc: java.sql.SQLException: Data type mismatch. (2015-02-04) | [
"",
"sql",
"jdbc",
"groovy",
"soapui",
""
] |
I have a table `Customers` that contains the fields `customer_id`, `first_name`, `last_name`, `referred_by`.
What I want to do is to display full name of the customers who have been referred and the full name of the referrer.
For example I want something like this :
```
id | first_name | last_name | referred_by
1 |... | Use join.
```
SELECT
CONCAT(c1.firstname, ' ', c1.lastname) AS 'Customer''s Name',
CONCAT(c2.firstname, ' ', c2.lastname) AS 'Referred By '
FROM customer c1 join customer c2 = c1.id = c2.referred_by
``` | If the referred\_by column contains an id value from the customer table, then it would be something like this:
```
select concat(c.firstname,' ',c.lastname) customer
, concat(r.firstname,' ',r.lastname) referred_by_customer
from customer c
left join customer r on r.customer_id = c.referred_by
``` | How to query a table referring to itself in MySql? | [
"",
"mysql",
"sql",
""
] |
I am trying to arrange the book title in alphabetical order through oracle pl/sql function but want to avoid 'a', 'an', 'the' in the sorting. I have tried create function using different functions such as LTRIM, TRIM, REPLACE but the the book title are not sorted when I use ORDER BY FUNCTION NAME.
Code for Create func... | Why use a function at all? Also, be sure to test with titles that begin with the letter 'A' but not the *word* 'A ' and so forth. The `ltrim( string, 'A ' )` function will return 'Great Day' when passed 'A Great Day' but it will also return 'nother Great Day' when passed 'Another Great Day'. This will not work as you e... | Try with this
```
CREATE OR REPLACE FUNCTION sort_string(
p_title IN VARCHAR2)
RETURN VARCHAR2
AS
BEGIN
RETURN trim(REPLACE(REPLACE(REPLACE(p_title,'A ',''),'An ',''),'The ',''));
END;
/
CREATE TABLE book
( bookid INT, book_title VARCHAR(100)
);
INSERT
INTO book VALUES
(
1,
'A reference to th... | how to sort book titles in order without a, an, the using oracle pl sql function | [
"",
"sql",
"oracle",
"sorting",
"plsql",
"sql-order-by",
""
] |
I need to normalize a table that contains anagraphic data.
Here is a sample table with some rows:
```
Id LastName FirsName Address Email Tel Mobile Age
1 Rossi Mario Via Milano NULL 123456 NULL 41
2 Rossi Mario NULL rm@test.it 123456 NULL NULL
3 Rossi Mario Via Mil... | If you are considering `FirstName` and `LastName` as key identifiers then you can write as:
```
SELECT MIN(Id),
T1.LastName ,
T1.FirsName,
SUBSTRING ((SELECT DISTINCT CASE WHEN T2.Address IS NULL
THEN '' ELSE ','+ T2.Address END
FROM @Test T2
WHERE T1.LastN... | I think this might helps you:-
```
UPDATE TAB_NAME
SET ID = MIN(ID), LastName = MAX(LastName), FirsName = MAX(FirsName)
Address = MAX(Address), Email = MAX(Email), Tel = MAX(Tel),
Mobile = MAX(Mobile), Age = MAX(Age)
WHERE COND.;
``` | Merge records in SQL SERVER | [
"",
"sql",
"sql-server",
"merge",
""
] |
I have this query which finds the number of properties handled by each staff member along with their branch number:
```
SELECT s.branchNo, s.staffNo, COUNT(*) AS myCount
FROM Staff s, PropertyForRent p
WHERE s.staffNo=p.staffNo
GROUP BY s.branchNo, s.staffNo
```
The two relations are:
```
Staff{staffNo, fName, lName... | This is a bit long for a comment.
`COUNT(*)` is counting the number of rows in each group. It is not specifically counting any particular column. Instead, what is happening is that the `join` is producing multiple properties, because the properties are what cause multiple rows for given values of `s.branchNo` and `s.s... | `GROUP BY` clauses partition your result set. These partitions are all the sql engine needs to know - it simply counts their sizes.
Try your query with only `count(*)` in the `select` part.
In particular, `COUNT(*)` does *not* produce the number of distinct rows/columns in your result set! | How does GROUP BY use COUNT(*) | [
"",
"sql",
""
] |
I am working on a sql statement where I'm trying to grab all projects less than or equal to the development date. However, I'm getting an error
"Data type mismatch in criteria expression"
I've searched and searched, but I haven't been able to find anything.
The raw results look similar to this:
```
| Title | devTer... | Ok I figured out the issue. From the comments under my question, I was able to think about the Nz() function. The final query looks like
```
SELECT *
FROM projects
WHERE Date() >= DateSerial(Left(Nz(devTerm, "1990"),4),Right(Nz(devTerm, "01"),2), 1)
AND Date() < DateSerial(Left(Nz(pilotTerm, "1990"),4),Right(Nz(pilotT... | So far the only way I have been able to recreate this issue is by making a quick test function to see what possibilities it could be. From this I feel like there has to be a record that is blank or invalid, the function to recreated this is as follows:
```
Public Function Test()
If Date >= DateSerial(Left("201401... | Access Date Comparison Error | [
"",
"sql",
"date",
"ms-access",
"ms-access-2013",
""
] |
I have a table related to reviews made by a person. The table has the following fields: **reviewId**, **personId**, **isComplete**, where **isComplete** is a boolean indicating whether the particular person completed his review.
Imagine the following values:
```
ReviewID | PersonID | isComplete |
1 1 ... | ```
SELECT DISTINCT(PersonID) FROM reviews
WHERE PersonId NOT IN (
SELECT DISTINCT(PersonID) FROM reviews WHERE isComplete = 0
)
``` | * Table A contains all records
* Table B contains all people who have at least 1 outstanding review.
* We use a left join and eliminate nulls so that what remains is only users who have records with no outstanding reviews...
.
```
SELECT Distinct A.PersonID
FROM TABLE A
LEFT JOIN Table B
on A.PersonID = B.PersonId... | Construct SQL query to find records that all have the same value | [
"",
"mysql",
"sql",
"subquery",
""
] |
I am trying to compute a value in select statement itself but surprisingly it results in 0.
```
SELECT Top(1) Name,
LEN(Name) AS Equals,
Abs(LEN('Johny') - LEN(Name)) AS NotEquals,
LEN(Name)/(Abs(LEN('Johny') - LEN(Name)) + LEN(Name)) As Match
FROM Demo
WHERE Name = LEFT( 'Johny' , LEN(Name) )
ORDER BY LEN(Name) D... | you are trying to divide integer values where divisor > dividend
try cast one value to float
```
SELECT Top(1) Name,
LEN(Name) AS Equals,
Abs(LEN('Johny') - LEN(Name)) AS NotEquals,
cast(LEN(Name) as float)/(Abs(LEN('Johny') - LEN(Name)) + LEN(Name)) As Match
FROM Demo
WHERE Name = LEFT( 'Johny' , LEN(Name) )
ORD... | Because your calculation uses integers:
```
4/5 = 0
```
All behind the comma is removed | Computing value in select statement t-sql | [
"",
"sql",
"ssms",
""
] |
I'm pretty new to SQL. I'm trying to write a query that will grab records associated that share an value with the sought after record in a single query.
For example below, if one record has a 'No' in it, I want it to to then return all records that share a common 'Letter'
```
Letter;Present
A;Yes
A;No
A;Yes
B;Yes
B;Y... | You will need to use a subquery for that..
```
SELECT a.letter, a.present
FROM yourTable a
WHERE a.letter IN (SELECT letter
FROM yourTable
WHERE present = 'No');
```
What you do here is select all letters where `present = 'NO'` then you simply re-select from that group where your... | Use a sub-query to find those No letters. Then search for rows where values first character is in the found No letters.
```
select * from table
where letter in (select letter from table where present = 'No');
``` | Associated records | [
"",
"sql",
""
] |
I am using sql-server.I have a table looks like
```
StudentName Class score
Jim a1 80
Ann a1 83
Bill a2 90
```
I want to select student whose score is above the average score in his/her class. Here is my code:
```
Select a.StudentName
From Table a
inner Join Table b
On ... | Try something like this:
```
Select a.StudentName, TableAvg.class, a.score
From TableA a
inner Join (select class, avg(score) as AvgScore
From TableA
group by class) TableAvg
On a.score > TableAvg.AvgScore
and a.class = TableAvg.class
```
Untested code... | Sample data:
```
SELECT 'Jim' AS StudentName, 'A1' AS Class, 80 AS Score
INTO #Temporary
UNION ALL
SELECT 'Ann', 'A1', 83
UNION ALL
SELECT 'Bill', 'A2', 90
```
Actual query (without needing to join table twice)
```
SELECT *
FROM (
SELECT StudentName, Class, Score, AVG(CAST(Score AS FLOAT)) OVER(PARTITION BY Clas... | Inner join and Avg( ) function | [
"",
"sql",
"sql-server",
"inner-join",
"average",
""
] |
I'm attempting to perform a GROUP BY on a join table table. The join table essentially looks like:
```
CREATE TABLE user_foos (
id SERIAL PRIMARY KEY,
user_id INT NOT NULL,
foo_id INT NOT NULL,
effective_at DATETIME NOT NULL
);
ALTER TABLE user_foos
ADD CONSTRAINT user_foos_uniqueness
UNIQUE (u... | Try:
```
SELECT *
FROM (
SELECT t.*,
row_number() OVER( partition by user_id, foo_id ORDER BY effective_at DESC ) x
FROM user_foos t
)
WHERE x = 1
``` | Postgres has a very nice feature called `distinct on`, which can be used in this case:
```
SELECT DISTINCT ON (uf."user_id", uf."foo_id") uf.*
FROM "user_foos" uf
ORDER BY uf."user_id", uf."foo_id", uf."effective_at" DESC;
```
It returns the first row in a group, based on the values in parentheses. The `order by` cla... | Trouble performing Postgres group by non-ID column to get ID containing max value | [
"",
"sql",
"postgresql",
"window-functions",
""
] |
I wanted to remove/ignore the seconds and milliseconds coming from GETDATE() SQL function.
When I executed,
```
SELECT GETDATE()
```
output will be like
```
2015-01-05 14:52:28.557
```
I wanted to ignore seconds and milliseconds from above output. What is the optimize and best way to do this?
I have tried to do th... | I'd either use the `DATEADD`/`DATEDIFF` trick that [Codo has shown](https://stackoverflow.com/a/28338137/15498) or just cast it to [`smalldatetime`](https://msdn.microsoft.com/en-GB/library/ms182418.aspx)1:
```
select CAST(GETDATE() as smalldatetime)
```
I'd avoid anything that involves round-tripping the value throu... | Try this:
```
SELECT dateadd(minute, datediff(minute, 0, GETDATE()), 0)
```
The query uses the fact that `DATEDIFF` return the number of minutes between two dates, ignoring the smaller units. `0` is a fixed date in the past.
It can be easily adapted to other time units. | Ignore seconds and milliseconds FROM GETDATE() in SQL | [
"",
"sql",
"t-sql",
""
] |
I am trying to write this SQL code:
```
create table Users
{
UserID int primary key identity(200,1),
FirstName varchar(20) not null,
LastName varchar(20) not null,
BirthDate dateTime not null,
HomeTown varchar(30),
WorkPlace varchar(40),
Email not null
}
```
The problem is that next the `{... | You need brackets not braces - <http://www.w3schools.com/sql/sql_create_table.asp> Also a data type for email
I.e.
```
create table Users
(
UserID int primary key identity(200,1),
FirstName varchar(20) not null,
LastName varchar(20) not null,
BirthDate dateTime not null,
HomeTown varchar(30),
WorkPlace varchar(40),
E... | You have not specified the `datatype` for `Email` columnn.
Use ()instead of {}. | Sql syntax error - expecting ( or as | [
"",
"sql",
"sql-server",
"syntax-error",
""
] |
I want to filter out results obtained from two different queries and obtain the total count. Below are my two queries:
```
Query 1
select count(*)
from table1 oow
where oow.status='completed'--134 records
Query 2
select count(*)
from table2 oow
join #temp re
on oow.order=re.orde... | Try this:
```
select count(*)
from table1
where not exists
(select 1
from #temp re
where re.order = order and status = 'Completed')
```
This query just returns those rows which exist in table1 but do not exist in #temp, based on the order value and filter condition. Therefore, the above is equivalent to getting the ... | given the table alias oow I'm going to assume that both table1 in query1 and table2 in query2 are actually the same table. if that is the case, you could do it this way:
```
select count(*)
from
table2 oow
left join #temp re
on oow.order=re.order
where oow.status='completed'
and re.order is nul... | How to subtract result of first query and second query | [
"",
"sql",
"sybase",
""
] |
I have a SQL query that refers to the same table twice, and I need to alias the table to two separate aliases. I can't quite figure out how to compose this with Knex.
There's a 'Words' table and a 'Users' table. The Words table has two foreign keys, 'author\_id' and 'winner\_id', referencing the Users table's 'id' col... | There are [two ways](http://knexjs.org/#Builder-identifier-syntax) to declare an alias for identifier (table or column). One can directly give as aliasName suffix for the identifier (e.g. identifierName as aliasName) or one can pass an object { aliasName: 'identifierName' }.
So, the following code:
```
knex.select('... | I think I figured it out. In knex.js, say you specify a table like:
`knex.select( '*' ).from( 'Users' )`
Then you can just add the AS keyword within the quotes of the table name to alias it, like so:
`knex.select( '*' ).from( 'Users AS u' )`
..and you can do this for column names, too; so my original SQL would look... | Alias a table in Knex | [
"",
"sql",
"left-join",
"inner-join",
"knex.js",
""
] |
I have 3 columns (Date, Flag, cost)
The date starts from the beginning of the year, the flag is either daily or monthly and the cost.
For daily values it is fine. For monthly values, I would like to
Sum the entire monthly flaged values and divide by the number of days in that month. The resulted rate, populate it in t... | *If* I understand it well, this should give you the average per day of the "monthly" values:
```
SELECT "Cost" / EXTRACT(DAY FROM LAST_DAY("Date")) "cost_per_day",
LAST_DAY("Date") "month"
FROM T
WHERE "Flag" = 'MONTHLY'
```
Once you have that, you final query could be written like:
```
WITH monthly AS (
... | What's about this solution?
```
SELECT THE_DATE, Flag, COST,
CASE Flag
WHEN 'DAILY' THEN COST
WHEN 'MONTHLY' THEN
COST/EXTRACT(DAY FROM LAST_DAY(THE_DATE))
ELSE NULL
END AS AVG_COST
FROM THE_TABLE;
``` | Populating Monthly cost to daily records | [
"",
"sql",
"oracle",
""
] |
How to change column value by `CASE` command depending on condition without giving adding a new column to table?
The only way I know is by adding new column:
```
SELECT
t1.*
,CASE
what='costs' THEN amount*(-1)
ELSE
sales
END AS NewAmount
FROM t1
```
Is there a way to get the results as o... | Yes, there is way,
Instead of `select *`, use required column names only.
```
SELECT
t1.what
,CASE
WHEN what='costs' THEN amount*(-1)
ELSE
sales
END AS Amount
FROM t1
``` | Select just the columns that you want:
```
SELECT t1.what,
(CASE WHEN what = 'costs' THEN amount*(-1)
ELSE sales
END) AS Amount
FROM t1
``` | How to use CASE without adding new column to table in SQL | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
I need to count how many weeks and listing them up in a table with their respective date range.
so what i have for now is
```
select countinous_weeks, decode(countinous_weeks-52,0,trunc(countinous_weeks),trunc(countinous_weeks)+1)
from (
select (TO_DATE('01-01-1995', 'DD/MM/YYYY') - TO_DATE('01-01-1994','DD/MM/YYYY')... | This is interesting. It has got the following things involved -
1. **DATE ROW GENERATOR**
2. **Week number**
3. **ROW\_NUMBER()** to assign rank to dates in each set of week
4. Finally **LISTAGG** to aggregate the rows fetched from step 3
Let's see it working -
```
SQL> WITH DATA AS
2 (SELECT to_date('01/01/199... | Here is the query.
```
SELECT LEVEL , to_char( TO_DATE('01-01-1995', 'DD/MM/YYYY') + ( level * 7 ) - 7) || ' until ' || to_char( TO_DATE('01-01-1995', 'DD/MM/YYYY') + ( level * 7 ) - 1 ) as range
FROM DUAL
CONNECT BY LEVEL <= ( select (TO_DATE('01-01-1995', 'DD/MM/YYYY') - TO_DATE('01-01-1994','DD/MM/YYYY'))/7 cou... | querying how many weeks between a date range and showing them their dates | [
"",
"sql",
"oracle",
"date",
""
] |
I want to compare datetimes and delete the rows thats more than 72 hours old. Then I want to update another table boolean "HasClone". How do I get the ints (ID's) from the first selection into the other? see code below:
```
SELECT Allocation_plan_details_Clone.Allocation_plan_id AS ID
FROM Allocation_plan_de... | If I understood your question right I think what you want is this:
```
UPDATE Allocation_plan
SET HasClone = 0
WHERE allocation_plan_id IN (
SELECT Allocation_plan_details_Clone.Allocation_plan_id
FROM Allocation_plan_details_Clone
WHERE DATEDIFF(hour, start_date, GETDATE()) > 72
)
``` | This answer is putting the Allocation\_plan\_id's into a table variable while the rows are deleted.
The transaction assure that the data doesn't get deleted without updating the Allocation\_plan table.
I rewrote your WHERE statement to perform better.
```
begin transaction t
DECLARE @deleted table(Allocation_plan_i... | Get Selected values in SQL | [
"",
"sql",
"sql-server",
"azure-sql-database",
""
] |
The following code is throwing an error:
```
select *
from inPersonMedChangeNotes as IP
where
(IP.[Date], IP.Patient) not in (select EncounterDate, Patient
from tbl_patients_clinic_visit_records as VC
join tbl_patients as PS on VC.PatientId... | You can do this with a left join:
```
SELECT *
FROM inPersonMedChangeNotes as IP
LEFT JOIN tbl_patients_clinic_visit_records as VC ON IP.[Date] = VC.EncounterDate AND IP.Patient = VC.Patient
left join tbl_patients as PS on VC.PatientId = PS.PatientId_this
WHERE VC.EncounterDate IS NULL
``` | Following the same structure of your query, you can use `not exists`:
```
select *
from inPersonMedChangeNotes IP
where not exists (select 1
from tbl_patients_clinic_visit_records
where ip.patient = vc.patientid and
ip.[date] = vc.encounterdate
... | How to check for combination of column values in sql server table | [
"",
"sql",
"sql-server",
""
] |
I got a question: if I have a `Product` table in SQL which has columns `Product ID`, `TotalPrice`, `NumberOfUnits`
Now I need to calculate the `unitPrice` of the product.
This can be calculated by dividing the `TotalPrice` by `NumberOfUnits`.
Now the question is: if the `totalPrice` is `Null` and `NumberOfUnits` is ... | Null = NULL.
```
SELECT NULL / 45
```
Result
```
Column1
NULL
```
Handling would be...
```
SELECT IsNull(NULL, 0) / 45
```
Result
```
Column1
0
``` | 1. Null/45 = NULL
2. anynumber/null = null
Your table structure is incorrect, you need to create the table in a way that it cannot accept null for price as well as quantity.
Rest will have a big discussion :) | Divide Null by a number in SQL | [
"",
"sql",
"null",
"divide",
""
] |
I have a varchar2 date field 'Created\_Date' of the format 'MM/DD/YYYY HH24:MI' in an oracle table.Now, I want all the fields where date range is between 1-JAN-2014 to 31-MAR-2014.
I have used the below query & I know some of my dates of 31st March 2014 are getting missed.
```
Select *
from Table1
where to_date(Crea... | What I think is happening is that your `VARCHAR2` "dates" have time components, in which case they could fall after 31 March 2014. I would suggest you do the following:
```
SELECT * FROM table1
WHERE TO_DATE(created_date, 'MM/DD/YYYY HH24:MI') >= '01-JAN-2014'
AND TO_DATE(created_date, 'MM/DD/YYYY HH24:MI') < '01-... | Of course dates on Mar 31 are not shown -- if they have a time component. By using `between` you are only getting up to midnight when Mar 31st begins. That is how dates work and how between works.
Here are two solutions. First, only use the date:
```
where to_date(Created_Date, 'MM/DD/YYYY') between date '2014-01-01'... | Last day getting dropped while casting varchar 2 date format 'mm/dd/yyyy hh24:mi' | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I have the following query:
```
SELECT TOP 3
Person.Name AS PersonName,
SUBSTRING(CAST(Person.BirthDate AS varchar(38)), 1, 2) AS CenteryBorn,
Person.BirthDate AS CompleteDateTimeBorn
FROM Person
```
What I want is something like this, with `CenteryBorn` column having the first two digits of the datetime... | How about using:
```
YEAR(BirthDate)/1000
``` | you can use datepart function instead
```
substring(cast(datepart(y,person.birthdate) as varchar),1,2)
``` | TSQL - Make Casting datetime as varchar not return friendly format | [
"",
"sql",
"t-sql",
"datetime",
"formatting",
"substring",
""
] |
I have the following procedure which is executed on a button click (button1). After being prompted to log into the database, delphi throws the the following error:
> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''AlphaMc'
>
> SELE... | The MySql [identifier](http://dev.mysql.com/doc/refman/5.0/en/identifiers.html) quote character is the backtick, try
```
ADOQuery1.SQL.Add('SELECT * FROM `AlphaMc111`');
``` | Don't use quotes to escape column or table names. Use backticks
```
ADOQuery1.SQL.Add('SELECT * FROM `AlphaMc111`');
```
Quotes are string delimiters. | Why does This SQL query give a syntax error | [
"",
"mysql",
"sql",
"delphi",
"delphi-7",
""
] |
I have a table like this :
```
id Date Qty
1 Feb 25 2015 12:00AM 34
2 Feb 27 2015 12:00AM 34
3 Mar 17 2015 12:00AM 153
4 Mar 27 2015 12:00AM 68
5 Apr 3 2015 12:00AM 153
6 May 6 2015 12:00AM 153
```
I want select the first date where I will have enough Qt... | The issue is that when you create your ##temp tables you're using the `nvarchar` type instead of `datetime` (and `int` for qty). The best remedy would be to use the correct types when you create the tables, if that won't work you can use casts in the query like this:
```
SELECT top 1
cast(t1.Date as datetime),
T1.Qty... | As I said in my comment you need to cast / convert your Date field to a date or datetime for the ordering to work properly:
```
SELECT top 1
T1.Date,
T1.Qty
,SUM(cast (T2.Qty as int)) AS cumulqte
FROM
##temptest3 T1
INNER JOIN ##temptest3 T2
ON T1.Date >= T2.Date
GROUP BY T1.id, T1.Date, T1.Qty
HAVING SU... | SQL server query, select first date where enough stock | [
"",
"sql",
"sql-server",
"select",
""
] |
I want to get a "totals" report for business XYZ. They want the season,term,distinct count of employees, and total employee's dropped hours, only when dropped hours of anemployee != any adds that equal the drops.
trying to do something like this:
```
select year,
season,
(select count(distinct empID)
from tab... | I managed to work it out with a bit of analytics .. ;)
```
with tableA as (
select 2015 year, 1 season, 1234 empID, 2 hours , 'Add' code from dual union all
select 2015 year, 1 season, 1234 empID, 3 hours , 'Add' code from dual union all
select 2015 year, 1 season, 1234 empID, 4 h... | I think you can do what you want with just conditional aggregation. Something like this:
```
select year, season, count(distinct empID) as Employees,
sum(case when code like 'Drop%' then hours end) as Dropped
from tableA
group by year, season;
```
It is hard to tell exactly what you want, because you do not ha... | SQL SUMs in where clause with conditionals | [
"",
"sql",
"oracle",
"sum",
"subquery",
""
] |
Consider the following employee\_history table:
```
╔═════════╦═══════╦═════════════╦═══════════════╦══════╗
║ ID ║ idEMP ║ startDate ║ endDate ║ Money║
╠═════════╬═══════╬═════════════╬═══════════════╬══════╣
║ 1 ║ 1 ║ 2013-11-01 ║ 2013-11-25 ║ 100 ║
║ 2 ║ 1 ║ 2013-11-25 ║ 2014... | Sth like this should work:
```
SELECT *
FROM employee_history
WHERE startDate <= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@searchDate)+1,0)) AND
(endDate > CAST(CAST(YEAR(@searchDate) AS varchar) + '-' + CAST(MONTH(@searchDate) AS varchar) + '-01' AS DATETIME)
OR endDate is null)
```
The following expresion:... | ```
SELECT money, startdate, substring_index(startdate,'-','-1') as date
FROM table
WHERE date = '2014-01'
```
the following code sorts it by month
try this, I kinda of deciphered what you meant.
I assume this is what you want :) | Getting history data for a specific date(YEAR AND MONTH) from a table | [
"",
"sql",
"sql-server-2008",
""
] |
Not sure how to title or ask this really. Say I am getting a result set like this on a join of two tables, one contains the `Id` (C), the other contains the `Rating` and `CreatedDate` (R) with a foreign key to the first table:
```
-----------------------------------
| C.Id | R.Rating | R.CreatedDate |
----------------... | You need a CTE with a ROW\_NUMBER():
```
WITH CTE AS (
SELECT ID, Rating, CreatedDate, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY CreatedDate DESC) RowID
FROM [TABLESWITHJOIN]
)
SELECT *
FROM CTE
WHERE RowID = 1;
``` | If you are using SQL Server 2008 or later, you should consider using windowing functions. For example:
```
select ID, Rating, CreatedDate from (
select ID, Rating, CreatedDate,
rowseq=ROW_NUMBER() over (partition by ID order by CreatedDate desc)
from MyTable
) x
where rowseq = 1
```
Also, please unde... | SQL Query: get the unique id/date combos based on latest dates - need speed improvement | [
"",
"sql",
"sql-server",
"performance",
""
] |
i'm developing a database search page (using jsp), in this search page users will have multiple search conditions/options in the form of a drop-down list, those options can be left unselected (null in other words), if they're left unselected the complete column should be retrieved. To achieve this i'm using ifnull() fu... | Some details on Sas answer. In SQL a null is a special value, and no int or either string can ever be equal to NULL.
In a query, you must use the special construct `IS NULL` to test for null values because `column = NULL` will never be true.
When using home variables, you must explicitely set them to NULL with the`se... | Try set null:
```
prepStmt.setNull(1, Types.VARCHAR)
``` | SQL IfNull() function doesn't recognize null strings | [
"",
"mysql",
"sql",
"database",
"jsp",
"web",
""
] |
I have a table `matches` that I want to get from it the users that has the best score:
```
SELECT userId,SUM(score) AS score FROM `matches` GROUP BY userId ORDER BY score DESC
```
This output 2 columns `userId` and `score`. Good.
Now I have a `users` table, and I want to have a more detailed output of that `userId`. ... | ```
SELECT userId, firstName, lastName, phone, address, SUM(score) AS score FROM matches join users on matches.user_id = users.user_id GROUP BY userId ORDER BY score DESC
``` | You could just `JOIN` the tables like this:
```
SELECT
matches.userId,
SUM(matches.score) AS score,
users.firstName,
users.lastName,
users.phone,
users.address
FROM
`matches`
JOIN users
ON `matches`.userId=users.userId
GROUP BY
matches.userId,
users.firstName,
use... | SELECT query from 2 tables | [
"",
"mysql",
"sql",
""
] |
I have a column that is VARCHAR2 and the string inlcudes a date and time. I have extracted the date and now wish to populate a new column solely with the date and time.
So far I have:
```
alter table t
add cb_time
as
select substr(t.notes, 24, INSTR(t.notes, 'for')-1)
from Mytable t
```
this results in error ORA 200... | Since you are on 11g, and as you say that both columns are in same table. I would suggest, do not add a static column, rather add a **virtual column**.
So, you need not worry about the **insert** too. Oracle would give you the computed value without actually storing it.
Just add the virtual column as -
**EDIT** A cl... | An alternative method is to create `CB_TIME` as a virtual column. To do soan ALTER TABLE similar to the following is used:
```
ALTER TABLE T
ADD CB_TIME DATE GENERATED ALWAYS AS
(TO_DATE(SUBSTR(t.notes, 24, INSTR(t.notes, 'for')-1))) VIRTUAL;
```
Because virtual columns can't be INSERTed or UPDATEed, doing ... | How do I create a new column filled with the results of a query? | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
How do I select from multiple tables in different databases on the same server?
Also, Is there a way to have an identifying marker so I could see where the results came from?
So for example:
```
SELECT db1.table1.name, db2.table2.name, fromTbl
FROM db1.table1, db2.table2
WHERE db1.table1.name LIKE '%j%' OR db2.table... | You could use a UNION ALL and add in the database name like:
```
SELECT [columns_list], 'db1.schema.table1.name' AS [fromTbl]
FROM db1.schema.table1
WHERE db1.schema.table1.name LIKE '%j%'
UNION ALL
SELECT [columns_list], 'db2.schema.table2.name' AS [fromTbl]
FROM db2.schema.table2
WHERE db2.schema.table2.name LIKE '... | Doing a union seems like your best bet here. A union will combine the results of two queries.
```
select name, 'table1' as fromTbl
from db1.schema.table1
where name like '%j%'
union --or union all depending on what you want
select name, 'table2' as fromTbl
from db2.schema.table2
where name like '%j%'
``` | SQL statement to select from 2 different tables, from two different databases (same server) | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I have a Table named Example that has a over 5M rows.
I want to know the most efficient way to create a new `DateTime` column that does not allow nulls and has a default value of Now. just setting the value would fail due to the amount of rows.
The plan I have in mind would involve:
1) creating a new column that allo... | To work though a large table with a sequential ID, applying updates in batches, this approach will work:
```
DECLARE @startID bigint
DECLARE @endID bigint
SELECT @startID=min(ID) from Example
WHILE @startID IS NOT NULL BEGIN
SELECT @endID=MAX(ID) FROM (
SELECT top(1000) ID from Example where ID>=@startID ORDER... | I would suggest:
```
ALTER TABLE Example ADD COLUMN RecordDate datetime NOT NULL DEFAULT getdate();
```
No matter how you attempt this, you are going to have to rewrite all the data records to add the extra bytes on each page for the value -- even if the value is NULL.
I had a thought that the following would minimi... | Set value to a new datetime column in a table with over 5 million rows | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I am using sql-server.I have a table looks like:
```
Name timestamp var1
Bill 2015-02-05 10:10:10 x1
Bill 2015-02-05 10:10:11 x2
...
Jim 2015-02-05 10:10:10 y1
Jim 2015-02-05 10:10:11 y2
...
John 2015-02-05 10:10:10 z1
John 2015-02-05 10:10:11 ... | Assuming `@duration` is a number of minutes that join should look like
```
....
and a.timestamp = DATEADD(mi,@duration,b.timestamp)
....
``` | If you're in SQL Server 2012 or newer you can solve this by using LAG() -window function, since with that you can compare the value of the row to the previous one, and if you order them properly, that's the one you're interested in.
<https://msdn.microsoft.com/en-us/library/hh231256.aspx>
It should probably be possib... | Try to avoid joining a large table | [
"",
"sql",
"sql-server",
""
] |
I need to find ranges of dates within a column and serialize them in a concise format (`start` - `end` for a range or `date` for a single-date range).
I have a CTE (`readings`) that returns a data set that resembles:
```
ID VALUE DATE
1234567 A 2012-05-09
1234567 A 2012-05-10
1234567 ... | You can use this query:
```
SELECT ID, VALUE, MIN([DATE]) AS startDate, MAX([DATE]) AS endDate
FROM (
SELECT ID, VALUE, DATE,
DATEDIFF(Day, '1900-01-01' , [DATE])- ROW_NUMBER() OVER( PARTITION BY ID, VALUE ORDER BY [DATE] ) AS DateGroup
FROM readings ) rGroups
GROUP BY ID, VALUE, DateG... | You'll probably be able to do this using a CLR aggregate.
Here's an example from MSDN which concatenates your data together. Just by changing the comma to a semi-colon, you could have your current format with a much cleaner query.
<https://msdn.microsoft.com/en-us/library/ms165055%28v=vs.90%29.aspx>
Once that's in p... | Serialize dates in a 'range' format without using a procedure | [
"",
"sql",
"sql-server",
"sql-server-2012",
""
] |
Lets have following sample table:
```
Person Quantity
A 1
B 2
C 3
D 4
E 5
```
Result should be:
```
PersonAggregate
1 (0+Quantity of PersonA)=sumA
3 (sumA+Quantity of PersonB)=sumB
6 (sumB+Quantity of PersonC)=sumC
10 (sumC+Quantity of PersonD)=sumD
15 (sumD+Quantity of Per... | Most versions of SQL support cumulative sums as a window function:
```
select person, sum(quantity) over (order by person) as cumesum
from sample;
```
You can can also do this with a correlated subquery:
```
select s.person,
(select sum(s2.quantity)
from samples s2
where s2.person <= s.person
... | this will obviously get the individual sums.
```
select person, sum(quantity)
from sample
group by person
order by person
```
i don't think your desired effect can be done in a set based way. a procedural language with cursor, like T-SQL or PLSQL, can do it easily.
i'd write a stored procedure and call it. | SQL: Column Sum | [
"",
"sql",
"select",
"aggregate",
""
] |
I have a system that has a User, Message, and MessageToken models. A User can create Messages. But when any User reads the Messages of others a MessageToken is created that associates the reader (User) to the Message. MessageTokens are *receipts* that keep track of the states for the user and that particular message. A... | Ok, so thanks to the help of R11 Runner I was able to come up with a solution, which required using pure SQL. I could not use the Squeel gem or ActiveRecord as there was no equivalent to SQL's NOT EXISTS operator, which was the crucial component missing.
The reason this works is because unlike the other solutions the ... | If you don't mind using 2 queries, a possible solution would be:
```
messages_not_written_by_user = Message.where.not(:user_id => @user.id)
messages_already_read_by_user = Message.where.not(:user_id => @user.id).includes(:message_tokens).where(message_tokens: {:user_id => @user.id, :read => true})
messages_not_read_b... | Ruby ActiveRecord Query with has_many Association | [
"",
"mysql",
"sql",
"ruby-on-rails",
"ruby",
"activerecord",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.