Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am trying to build a query that will look up a product\_subcategory based on a reference data in a user entered table and joining two tables together. My database is SQL Server 2012 Express.
First the `products` table has three columns: `Product_id` (unique identifier), `event_id` (INT data type), and `product_categ... | This should do the trick, you will just need to modify the `CAST(p.zone as nchar(10))` to insert the correct data type for your `category_lookup` column, in place of `nchar(10)`, as I assume the `zone` in `Products` is an `int` where as the lookup column is some string based column:
```
SELECT p.product_id, p.zone, p.... | Not tested but is this what you're looking for ?
```
select a.product_ID, a.zone, a.product_category, b.product_subcategory
from Products a
inner join Subcategory on ((a.zone = b.zone) and (a.product_category like b.category_lookup))
``` | SQL Lookup data in joined table based on LIKE value stored in joined table column | [
"",
"sql",
"sql-server",
"database",
"sql-server-2012-express",
""
] |
Is there a query that would merge previous arrays into a cumulative array, that would result in:
```
id array_field c_array
---------------------------------------------
1 {one,two} {one,two}
2 {three} {one,two,three}
3 {four,five} {one,two,three,four,five}
4 {six} {one,two,three,four,five,si... | It depends on what you work with. Seems like your base table holds text arrays `text[]`.
* You can use any aggregate function as window function. [Per documentation:](http://www.postgresql.org/docs/current/interactive/functions-window.html)
> In addition to these functions, any built-in or user-defined aggregate
> fu... | You can use [recursive CTE](http://www.postgresql.org/docs/current/static/queries-with.html).
[SQLFiddle](http://sqlfiddle.com/#!15/75fe3/2)
Data:
```
-- drop table if exists sample_data;
create table sample_data (id int, arr varchar[]);
insert into sample_data
values
(1,ARRAY['One','Two','Three']),
(2,AR... | Cumulative array from previous rows array? | [
"",
"sql",
"arrays",
"postgresql",
"window-functions",
""
] |
I have two tables:
* **Actions**
* **Hosts**
Sample data for the tables is as below:
**Actions**
```
| ID (bigint) | ACTION_TIME (datetime) | ACTION_NAME (varchar) |
-----------------------------------------------------------------------
| 1 | 2013-08-03 04:42:55 | test ... | ```
select MONTH, CRITICAL_COUNT, HIGH_COUNT from
(
select
YEAR(action_time) YEAR,
MONTH(action_time) MONTH,
SUM(critical_count) CRITICAL_COUNT,
SUM(high_count) HIGH_COUNT
FROM hosts H1 inner join actions A1 on A1.id = H1.action_id
WHERE DATE_SUB(CURRENT_DATE,INTERVAL 1 YEAR) <= action_ti... | Here is the working Fiddle:
<http://sqlfiddle.com/#!2/d179d/57>
And the query goes something like this:
```
SELECT
m.month,
ifnull(SUM(hosts.critical_count),0) as host_critical,
ifnull(SUM(hosts.high_count),0) as host_high
FROM
(SELECT
MAX(actions.action_time) as maxtime
FROM actions
GROUP BY MONTH(actions.action_ti... | Optimising a SQL query | [
"",
"mysql",
"sql",
""
] |
If I have a column in a table which is `tags` for example, and in that column an entry can be tagged with various keywords. Is it acceptable for an entry to have a list in that column instead of a single value?
So for example if I was putting a question into my table and I wanted to tag it as "math" and "physics", wou... | ## Never, never, never store multiple values in one column!
That is the 3rd rule of DB normalization.
Use another table to map the tags to the questions:
```
questions table
---------------
id
title
.....
tags table
----------
id
name
question_tags table
-------------------
question_id
tag_id
```
After that you ... | Its not really 3rd normal form to have a column full of tags. Rather, you might consider having a tags table that relates to the questions table. Consider the following tables. This sets up a many to many relationship between questions and tags.
```
Questions:
QuestionID|*
Tags:
TagID|TagText
QuestionTags:
QuestionI... | Is it acceptable to have a list in a MySQL column? Are lists searchable by SQL query? | [
"",
"mysql",
"sql",
"database",
""
] |
How do I structure an SQL statement to run across multiple flat unrelated tables and display the result with the result of the select and the name of the table where the result came from.
The scenario is such that I have several tables with the same column name in each. It is data that I have received from outside par... | You are looking for dynamic SQL. Assemble your query from the system catalog automatically:
```
SELECT string_agg('SELECT student_name, '''
|| c.oid::regclass || ''' AS tbl, pid FROM '
|| c.oid::regclass
|| $$ WHERE student_name = 'John Doe'$$
,... | Just add a literal value to each select that describes the source table:
```
select student_name, 'Table 1', pid
from table1
where ...
union
select some_name, 'Table 2', pid
from table2
where ...
union
...
``` | Search across multiple tables and also display table name in resulting rows | [
"",
"sql",
"postgresql",
"database-design",
"dynamic-sql",
""
] |
I have a Google Spreadsheet and I want to run a `QUERY` function. But I want the `WHERE` statement to check a series of values. I'm basically looking for what I would use an `IN` statement in SQL - what the `IN` equivalent in Google Spreadsheets? So right now I have:
```
=QUERY(Sheet1!A3:AB50,"Select A,B, AB WHERE B='... | Great trick Zolley! Here's a small improvement.
Instead of:
=CONCATENATE(G3,"|",G4,"|",G5,"|",G6,"|",G7)
we can use
=TEXTJOIN("|",1,G3:G7)
That also allows us to work with bigger arrays when adding every cell into the formula one by one just doesn't make sense.
UPD:
Going further I tried to compose two formulas ... | Although I don't now the perfect answer for that, I could find a workaround for the problem, which can be used in small amount of data (hope that's the case here :) )
First step: You should create a "helper cell" in which you concatenate the G4:G7 cells with a "|" character:
=CONCATENATE(G3,"|",G4,"|",G5,"|",G6,"|",G... | Query with range of values for WHERE clause? | [
"",
"sql",
"google-sheets",
""
] |
Let us say I have a table called `Employee` in Oracle with following structure.
```
EMPLOYEE:
NAME VARCHAR2(60)
DOB TIMESTAMP
SAL NUMBER
```
I want a query that selects all the employees whose DOB falls on last day of month.
i.e. (1/31, 2/28 or 2/29 based on year, 3/31 ....) | The way I'd approach this would be to add a day to it then see if the day of the month is the 1st.
I don't know Oracle specifically, but since you said general idea in MSSQL I'd do `datepart(d, dateadd(day, 1, DOB)) = 1` | In oracle `Last_day()` function:
```
SELECT * FROM table WHERE DOB=Last_day(DOB)
``` | select all the employees whose date of birth falls end of month | [
"",
"sql",
"oracle",
""
] |
is there a way can we convert Datetime to (dd/MM/yyyy AM/PM) format
for example 18/03/2014 AM in SQL | For MYSQL:
```
select DATE_FORMAT(NOW(), '%d/%m/%Y %p')
```
For SQL SERVER
```
SELECT convert(varchar(20), GetDate(), 103) + ' ' + substring(convert(varchar(30), GetDate(), 9), 25, 2);
```
For Postgres:
```
SELECT TO_CHAR(NOW(), 'dd/mm/yyyy AM')
``` | For Microsoft SQL Server you can use
```
select CONVERT(VARCHAR(24), GETDATE(), 100)
``` | How to Show Date with AM/PM instead of specifying time in SQL | [
"",
"sql",
"sql-server",
""
] |
Database: MSSQL server 2012;
Isolation level: READ\_COMMITTED\_SNAPSHOT
Now I have a table "COV\_HOLES\_PERIODDATE". It has a composite primary key which is also a clustered index. No other indexes on this table.
There are many threads(via Java) working concurrently. Each thread will first do a "select for update" o... | The investigation documented in the comments lead to the following answer:
You're passing in parameters which do not match the corresponding columns in type. This leads to implicit conversions and a range seek on the clustered index. "Seek" mean that a subset of the index will be scanned. It does not necessarily imply... | `ROWLOCK` never gives you an absolute guarantee of locking only this particular row(s) that you operate on. This is even stated on [MSDN](http://technet.microsoft.com/en-us/library/ms187373.aspx):
> Lock hints ROWLOCK, UPDLOCK, AND XLOCK that acquire row-level locks may place locks on index keys rather than the actual... | Rare and elusive deadlocks (select for update; then update) in case of multiple concurrent transactions | [
"",
"sql",
"sql-server",
"deadlock",
"database-deadlocks",
""
] |
I'm trying to figure out an sql query that would allow me to sort data ascending order depending on what time is sorted in appointment\_time column, it has values like "00:00" - "23:00"
In my head it looks like this:
```
SELECT * FROM myTable ORDER BY appointment_time ASC
```
But I don't know how to make it understa... | They will sort fine as your query is written, easiest thing is to just give it a whirl and see what happens:
```
SELECT *
FROM myTable
ORDER BY appointment_time ASC
```
Demo: [SQL Fiddle](http://sqlfiddle.com/#!7/fdb0e/1/0)
Alphanumeric ordering has no problem with numbers stored in strings so long as they are zer... | > But I don't know how to make it understand that 00:00 is lower value than 00:01
If all you have is a time then an alphabetical sort should work just fine. If you *want* to convert to a DateTime you can use CONVERT:
```
select CONVERT(DATETIME, appointment_time , 108)
``` | Sort by / Order by time stored in database "00:00 - 23:00" | [
"",
"sql",
"sqlite",
""
] |
This is my method to delete a row from the database where appointment\_date is equal to a date that was passed in
```
public void deleteAllAppointments(String date) {
SQLiteDatabase db = this.getWritableDatabase();
String deleteAllQuery = "DELETE FROM " + TABLE_APPOINTMENTS + " WHERE appointment_date ... | `rawQuery()` just compiles the SQL but does not run it. To actually run it, use either `execSQL()` or call one of the `moveTo...()` methods on the cursor returned by `rawQuery()`.
For further info, see [What is the correct way to do inserts/updates/deletes in Android SQLiteDatabase using a query string?](https://stack... | For tasks such as insert or delete there are really great "convenience methods" like the [delete method](<http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#delete(java.lang.String>, java.lang.String, java.lang.String[])) already built in to the database.
```
public int delete (String t... | Why is such DELETE query not working? | [
"",
"android",
"sql",
"sqlite",
""
] |
I am learning how to write TSQL queries. I am trying to understand them in depth. This query that I got from a tutorial requires that I check for a NOT NULL in the second WHERE clause.
```
SELECT *
FROM Person.Person AS p
WHERE NOT p.BusinessEntityID IN (
SELECT PersonID
FROM Sales.Customer
WHERE PersonID ... | Understanding how NULL values are handled by SQL Server can be difficult for newcomers. A value of NULL indicates that the value is unknown. A value of NULL is different from an empty or zero value. No two null values are equal. Comparisons between two null values, or between a NULL and any other value, return unknown ... | A little change as shown below (`column not in`)
```
SELECT *
FROM Person AS p
WHERE p.BusinessEntityID NOT IN ( <-- Here
SELECT PersonID
FROM Sales.Customer
WHERE PersonID IS NOT NULL);
```
Your inner query returns all non-null personid and outer query getting all fields
from person table with restricti... | Query using IN keyword | [
"",
"sql",
"sql-server",
"t-sql",
"in-operator",
""
] |
I was wondering how to put a constraint on a column when making the table.
How would the create statement look if I want to say something like, make a table called name with column size, and size has to be greater than 10.
`CREATE TABLE name(size int);`
Where do i put the constraint? | You can include a constraint in your declaration right after you have specified the column name, like so:
`CREATE TABLE name(size int CHECK (size > 10));` | Just because I've encountered more headaches than is necessary with system-named constraints, here's how to do it and also name the constraint in the process:
```
create table Persons (
size int,
constraint [CK_Persons_Size] check ((size > 10))
)
``` | SQL CREATE statement with a constraint | [
"",
"sql",
"sql-server",
""
] |
I am currently doing a SUM CASE to workout a percentage, however the entire string returns zero's or ones (integers) but I don't know why. I have written the SQL in parts to break it out and ensure the underlying data is correct which it is, however when I add the last part on to do the percentage it fails. Am I missin... | ```
SELECT
SUPPLIERCODE,
(SUM(CASE WHEN ISNULL(DATESUBMITTED,0) - ISNULL(FAILDATE,0) <15 THEN 1 ELSE 0 END)) AS ACCEPTABLE,
COUNT(ID) AS TOTALSUBMITTED,
(SUM(CASE WHEN ISNULL(DATESUBMITTED,0) - ISNULL(FAILDATE,0) <15 THEN 1 ELSE 0 END)*1.0/COUNT(ID))
FROM SUPPLIERDATA
GROUP BY SUPPLIERCODE
```
You... | This is due to the fact that SQL Server is treating your values as `INT`s for the purpose of division.
Try the following and you will see the answer `0`:
```
PRINT 1018 / 1045
```
In order to allow your operation to work correctly, you need to convert your values to `FLOAT`s, like so:
```
PRINT CAST(1018 AS FLOAT) /... | T-SQL Sum Case Confusion | [
"",
"sql",
"t-sql",
""
] |
I have summed the values and this below query sum the values and returns zero if there are no values.
How can I round off the values for these columns.
Here is my Query :
```
isnull(sum([Old_Values]),0) [Old Values],
[New_Value] = isnull(sum([Yearly_Value]-[Previous_Year_Value]),0)
```
Even this query I use for cal... | ```
[Product_Price] =Round([Product_Profit]/4,0),
[Product_Profit] = Round([ActualValue] * 0.75,0)
``` | ```
you could use FLOOR() or CEILING()
```
like this !
```
[Product_Price] = FLOOR([Product_Profit]/4),
[Product_Profit] = FLOOR([ActualValue] * 0.75)
``` | Having roundoff values for columns | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I'm trying to get a list of posts and comments count for each one.
```
SELECT
theposts.id,
theposts.name,
(SELECT COUNT(*) FROM thecomments WHERE thecomments.post_id = theposts.id) AS comments
FROM theposts
```
The problem is: I have 20k posts and 30 millions comments. The query is extremely slow.
If I ... | The best way that I can think of is to create an index. You need an index on `thecomments(post_id)`:
```
create index thecomments_postid on thecomments(post_id);
```
This should change the query plan to just an index scan and go pretty quickly.
I also think that this will be faster than using `group by`, which is th... | First off is to check that you have indexes where appropriate. That's usually the most common problem.
Another problem is that you may well be running 20,000 sub-queries, depending on how smart your query analysis engine is.
You can achieve the same result in *one* query just by grouping your rows, such as with (depe... | mysql: simple sub-query very slow because has 30 million rows | [
"",
"mysql",
"sql",
""
] |
Maybe I'm totally wrong and it's not pssible to do in MySQL. But, what I wanted to do is to fill out column row base in a select query:
For example:
Table 1:
```
IdNode NodeName NodeContact NodeStatus Nodegroup
1 Machine1 IT 1 IT
2 Machine2 IT 0 IT
3 Ma... | You can use [triggers](http://dev.mysql.com/doc/refman/5.0/en/triggers.html) to do this - you'd create triggers for insert, update and delete on table 1 to update table 2.
This is generally a bad idea though - it's duplicating information around the database, denormalizing the schema.
Alternatively, you can create a ... | Use [multiple `UPDATE`](http://dev.mysql.com/doc/refman/5.5/en/update.html) syntax with selecting counts in subquery as a sample:
```
UPDATE
table2
INNER JOIN
(SELECT COUNT(1) AS gcount, Nodegroup FROM table1 GROUP BY Nodegroup) AS counts
ON table2.GroupName=counts.Nodegroup
SET
table2.NodesManag... | Automatic column value update in MySQL | [
"",
"mysql",
"sql",
""
] |
I'm working on sql server 2008 r2. I'm trying to split a row by 24 hours period ranges between **FromDate**, **Todate**.
For example, if a time row has given as below, (Range between **FromDate**, **Todate** is 4 days, so I want 4 rows)
```
ID FromDate Todate
---- ------------------------ ------... | Try this query:
```
WITH TAB1 (ID,FROMDATE,TODATE1,TODATE) AS
(SELECT ID,
FROMDATE,
DATEADD(SECOND, 24*60*60 - 1, CAST(CAST(FROMDATE AS DATE) AS DATETIME)) TODATE1,
TODATE
FROM TABLE1
UNION ALL
SELECT
ID,
DATEADD(HOUR, 24, CAST(CAST(TODATE1 AS DATE) AS DATETIME)) FROMDATE,
DATEADD(SECOND, 2*24*60*60-1, CAST(CAST(TOD... | <http://sqlfiddle.com/#!6/36452/2>
This should be what you need.
The first part of the query is a recursive CTE. This can be used to create the dates-data.
```
WITH CTEDays AS
(
SELECT CONVERT(date, '20140301') datevalue
UNION ALL
SELECT DATEADD(day, 1, C.datevalue)
FROM CTEDays C
WHERE DATEADD(day, ... | SQL Server , split a time duration row by 24 hour period | [
"",
"sql",
""
] |
My statement look like this,
```
update DATA_SOURCE tgt
set
tgt.DATA_SOURCE_NM=src.DATA_SOURCE_NM,
tgt.ODS_UPDATE_TS=src.ODS_UPDATE_TS
select DATA_SOURCE_NM,ODS_UPDATE_TS
from DATA_SOURCE_BKP src
where tgt.DATA_SRC_ID=src.DATA_SRC_ID;
```
I got following error message:
> error ^ found "SELECT" (at char 103) ex... | It works when I remove the line
> select DATA\_SOURCE\_NM,ODS\_UPDATE\_TS | Try this
```
update tgt
set
tgt.DATA_SOURCE_NM=src.DATA_SOURCE_NM,
tgt.ODS_UPDATE_TS=src.ODS_UPDATE_TS
from DATA_SOURCE tgt
inner join DATA_SOURCE_BKP src on tgt.DATA_SRC_ID=src.DATA_SRC_ID;
```
--where
may be you can add a where clause in the end to filter few more conditions | Error when updating table from another table | [
"",
"sql",
"netezza",
""
] |
My table is this:
```
CREATE TABLE studio(
s_id int NOT NULL IDENTITY(1,1),
name varchar(30),
country varchar(15),
income_money float(53),
movies int,
CONSTRAINT primaryKeyStudio PRIMARY KEY(s_id)
)
```
I want to insert values into table studio, is it bet... | The second way, i.e. this one
```
INSERT INTO studio(name,country,income_money,movies) VALUES ('Walt Disney Studios','USA',45041000.99,50)
```
where you list column names explicitly is better regardless of the identity column, for several reasons:
* **It is more readable** - Users who are not familiar with the table... | The first method requires a value for each column to be provided. If a new column is added to the table all insert statements must be rewrote to include the new column. Statements wrote using the second approach would remain functional since they specify columns explicitly.
I would recommend using the second approach. | insert rows into table with identity column | [
"",
"sql",
"sql-server",
""
] |
I'm trying to display the most popular product (format\_id) in a given month (JAN-14) and group them by a count of each format\_id.
Here is my Query :
```
select PRODUCT, AMOUNT
from (Select Order_108681091.Order_Date, order_line_108681091.Format_id as Product,
COUNT(*) AS AMOUNT FROM order_line_108681091
Inner J... | 1. You said you have the condition, so let's start with adding it.
2. There is no need to `ORDER BY`, so remove it.
3. Remove `Order_date` from the subquery `SELECT`
4. Use aliases
5. The subquery itself would be enough.
```
SELECT l.Format_id as PRODUCT,
COUNT(*) AS AMOUNT
FROM order_line_108681091 l
... | You have to specify the inner join:
```
inner join order_108681091 ON order_1078681091.ID = order_line_018681091.ID
```
or something like that. Also your where clause probably wont work unless you're storing that date as a string and not a datetime datatype. | Oracle SQL Missing Keyword | [
"",
"sql",
"oracle",
""
] |
I am writing:
```
Select datediff(hh,getutcdate(), End_Date) as "Duration"
from MasterTable
order by Duration
```
To get difference of hour values in ascending order. I get output,
```
Duration
--------
-259
-210
5
10
22
35
75
105
235
```
But I want, ordering has t... | If you do want the sequence, as you've indicated in the question, where it's all of the positive numbers in ascending order first, then the negative numbers in ascending order, it should be:
```
Select datediff(hh,getutcdate(),End_Date) as "Duration" from MasterTable
order by CASE WHEN Duration >= 0 THEN 0 ELSE 1 END,... | Understanding that what you need is to ignore *Duration* sign:
Try using ABS:
```
Select datediff(hh,getutcdate(),End_Date) as "Duration" from MasterTable order by ABS(Duration)
``` | Sorting Date Difference in SQL | [
"",
"sql",
"sql-server",
"datetime",
"datediff",
""
] |
I'm having an assignment for my sql class which i can't seem to figure out. This is the description of the select wanted:
Show all employees of which the salary is higher than the average of the colleagues in their department, only for the departments with at least 4 employees.
I've been able to find parts of the que... | Just put your second query in with an AND clause:
```
select ename
from emp
where sal > any (select avg(sal)
from emp
group by
deptno)
and deptno in (select deptno
from emp
group by
deptno having count(d... | You can use **Having Clause** in Conjunction with **Group By**
```
select ename
from emp
where sal > any (select avg(sal)
from emp
group by
deptno)
having count(*)>4;
``` | sql subqueries and group by | [
"",
"sql",
"oracle11g",
""
] |
A simplified example for illustration: Consider a table "fruit" with 3 columns: name, count and the date purchased. Need an alphabetical list of the fruits and their count the last time they were bought. I am a bit confused by the order of sorting and how distinct is applied. My attempt -
```
drop table if exists frui... | Try this:-
```
select f1.name,f1.count
from
fruit f1
inner join
(select name,max(dateP) date_P from fruit group by name) f2
on f1.name = f2.name and f1.dateP = f2.date_P
order by f1.name
```
**EDITED** for the last line :) | Try the following:
```
SELECT fruit.name, fruit.count, fruit.dateP
FROM fruit
INNER JOIN (
SELECT name, Max(dateP) AS lastPurchased
FROM fruit
GROUP BY name
) AS dt ON (dt.name = fruit.name AND dt.lastPurchased = fruit.dateP )
```
Here is a demo of this example on [SQLFiddle](http://sq... | Combining select distinct with group and ordering | [
"",
"sql",
"sqlite",
""
] |
I hope someone can help. I have an excel file with hundreds of items that looks like the below table, that shows the Style's Color/Size and it's QTY levels. But I need to take the corresponding header Sizes and match it with the Style and Color as well as it's QTY levels. Then format it into each row and **then copy th... | I was able to figure out what I need by just using excel and joining the color, price, then adding the corresponding size to each qty level with a pipe-delimiter separating each value. Then transposing it vertically then, using the text to column function in excel to separate everything out. | In SQL you can do something like this I think(sorry I am a little rusty)..
```
SELECT style, color, size, qty, length price,
FROM table_name
ORDER BY style DESC, color, size DESC, qty DESC, length, price;
``` | Excel, SQL - Change select header rows to columns and insert values for each column | [
"",
"mysql",
"sql",
"sql-server",
"excel",
"vba",
""
] |
I have a Database set up with a column for `Datetime`.
In my application a have a date selector.
The issue is that the Db uses American Date Format `(MM/DD/YYYY)` where as the app uses European Date Format `(DD/MM/YYYY)`.
Is there a way to set up the column in the database to use European date format?
I don't want ... | SQL Server doesn't store a `DateTime` in any string format - it's stored as an 8 byte numerical value, and a `DATETIME` is a `DATETIME` is a `DATETIME`.
The various settings (language, date format) only influence how the `DateTime` is shown to you in SQL Server Management Studio - or how it is parsed when you attempt ... | About "*YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME*":
Another option is the usage of the usual space as separator between data and time: YYYYMMDD HH:MM:SS or **YYYYMMDD HH:MM:SS.SSS*... | Getting European Date Format SQL | [
"",
"sql",
"sql-server-2008",
"date",
"datetime",
""
] |
how to calculate aggregate function using mysql database.The following query returns invalid use of group functions.
```
select avg(max(qty)) from tb_name.
``` | You do not have any groups in your statement and if you just read it like this you should understand why it is not yielding a sensible result:
You say `Give me the average of the maximum value for qty from tb_name`, but since you are not grouping by anything there is only one maximum value.
If you need both values in... | You can do the following:
```
SELECT AVG(qty) FROM tb_name
```
This will give you the average value of quantity
OR
```
SELECT MAX(qty) FROM tb_name
```
This will give you the maximum value of quanity
Using both AVG and MAX on the same table is both logically and syntax-wise incorrect. | how to use this aggregate function in mysql database | [
"",
"mysql",
"sql",
""
] |
I have problems on query. I need the result that shows top 1 for each records from the table that has same id. Here is the Table Description.
Table `people`:
```
id | name |
--------------
01 | john |
02 | alex |
```
Table `job`:
```
id | job | date start |
---------------------------------
01 |... | **Try this**
```
WITH j AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY id ORDER BY date_Start DESC) AS RowNumber,
id, job, date_start
FROM job
)
select p.id, p.name, j.job, j.date_start
from people p
inner join j
on p.id = j.id
and j.RowNumber = 1
```
As you re... | Try this
```
SELECT S.id,s.name,S.job,s.date_start
FROM
(
SELECT T2.id,T1.Name,T2.job,T2.date_start
from people T1 Left Join job T2 ON T1.id =T2.id
group by T2.date_start,T2.id,T1.name,T2.job
) AS S Inner JOIN
(
SELECT Max(date_start) AS date_start,id From job
Group by id
) AS T ON S.date_start = T.date_s... | select top 1 record for each record on 1 table | [
"",
"sql",
""
] |
I have a `user` table with a one-to-many relationship to a `log` table.
Essentially, every time a user record is updated, a record is inserted into the log table.
Right now what I’d like to do is update the user table with the most recent log entry, setting their current status and notes fields to the most recently l... | Select the MAX(id) in the WHERE clause of the UPDATE statement like so:
```
UPDATE
u
SET
u.status = l.status,
u.notes = l.notes
FROM
user u
INNER JOIN log l ON u.user_id = l.user_id
WHERE
l.id = (
SELECT
MAX(id)
FROM
log
WHERE
user_id = ... | You need to manually find the last record. A good way to do this is with `not exists`:
```
UPDATE user u INNER JOIN
log l
ON u.user_id = l.user_id
SET u.`status` = l.`status`, u.notes = l.notes
WHERE not exists (select 1
from log l2
where l2.user_id = ... | Update with JOIN from another table and get the most recent | [
"",
"mysql",
"sql",
""
] |
I did try to get the answer myself by googling it but i can't find the solution.
I've two table actually.
This is suppose students table
```
id | sname | cid
1 a 1
2 b 2
3 c 2
4 d 3
5 e 4
6 f 3
7 g 4
8 h 3
```
This is the class... | Try this:
```
SELECT * FROM
((SELECT C.id,C.sname as cname,S.sname as sname
FROM class C INNER JOIN students S on C.id=S.cid) T1
LEFT JOIN
(Select C.id,count(S.cid) as count
FROM class C INNER JOIN students S on C.id=S.cid
GROUP BY C.id) T2 on T2.id=T1.id)
ORDER BY sname
```
Result:
```
ID CNAME SNAME COUNT
1 ... | A join with a subquery for count should do:
```
SELECT
s.id `id`,
c.sname `cname`,
s.sname `sname`,
(SELECT COUNT(1) FROM students WHERE students.cid = c.id) `count`
FROM
students s
LEFT JOIN class c ON s.cid = s.id
``` | Show count value and multiple row in mysql | [
"",
"mysql",
"sql",
""
] |
I have a Patient activity table that records every activity of the patient right from the time the patient got admitted to the hospital till the patient got discharged. Here is the table command
```
Create table activity
( activityid int PRIMARY KEY NOT NULL,
calendarid int
admissionID int,
activitydescripti... | Try this !
```
select admissionId, calendarid, admitTime=
(select top(1) admitTime
from activity a1
where a1.admisionID=a.admissionID and a1.calendarID=a.calendarid),
dischargeTime=
(select top(1) dischargeTime
from activity a1
where a1.admisionID=a.admiss... | This should get you what you want, with a bit less of a performance hit than subqueries:
```
select a1.admissionId
,a1.calendarid
,a2.admitTime
,a3.dischargeTime
from activity a1
left join activity a2
on a1.calendarid = a2.calendarid
and a2.admitTime <> -1
left join activity a3
... | Troubleshooting SQL Query | [
"",
"sql",
"sql-server",
""
] |
I want the output of SQL statement based on some if else condition.
For Ex:
```
select salary from EMP
```
EMP table has a column DOJ.
Now I want the output as '-' if the DOJ is less than 90 days.
How can i do this ? | ```
SELECT CASE WHEN (DATEDIFF(DAY,DOJ,getdate()) < 90) then '-' else cast(Salary as varchar(15)) end as Salary
FROM EMP
``` | In sql-server
```
select *,case when DATEDIFF(DAY,DOJ,getdate()) <=90 then '-' else null end as mytest
from tbale
``` | SQL statement with if else | [
"",
"sql",
"if-statement",
""
] |
I have a table called #CSVTest\_Data.
I wish to replace the content of that table with the result of the following query:
```
SELECT FirstTimeTaken,
LatestTimeTaken,
Market,
Outcome,
Odds,
NumberOfBets,
VolumeMatched,
InPlay
FROM #CSVTest_Data
EXCEPT
SELECT Odd... | Instead of seeking to replace a table, using a query based on the same table, just do a `DELETE`:
```
DELETE #CSVTest_Data
FROM #CSVTest_Data d
WHERE EXISTS( SELECT * from Data d2 WHERE
d.FirstTimeTaken = d2.OddsFirstTimeTaken AND
d.LastTimeTaken = d2.OddsLastTimeTaken AND
d.Market = d2.MarketName AND
... | First, the table #CSVTest\_Data must have the same number of columns as your SELECT query...
Then, you add at the top of your query this:
```
INSERT INTO #CSVTest_Data
``` | Replace content of a table with the results of a query in SQL Server | [
"",
"sql",
"sql-server",
""
] |
Is it possible to insert a record including timestamps into the database using usual statements? I don't want to use PreparedStatements.
My current query:
```
INSERT INTO CUSTOMER VALUES('some name',1965-10-31 01:00:00.0);
```
At the moment I get the error
> om.mysql.jdbc.MysqlDataTruncation: Data truncation: Incor... | You forgot the quotes around the date
```
INSERT INTO CUSTOMER
VALUES('some name', '1965-10-31 01:00:00.0');
``` | Try like this
```
INSERT INTO CUSTOMER VALUES('some name','1965-10-31 01:00:00');
``` | Insert timestamp without prepared statement | [
"",
"mysql",
"sql",
"jdbc",
"timestamp",
""
] |
I have a table 'Goods' with different information about goods (name, price, etc). I need to create a view at the same scheme as table 'Goods' has. But the view must be empty. And when user adds new good to the view it is saved in table 'Goods', but the view remains empty when user opens it next time. So main idea is no... | Assuming your on a database system that supports a concept like SQL Server's [`CHECK OPTION`](http://technet.microsoft.com/en-us/library/ms187956.aspx), and you're allowed to create a view that *doesn't* have that option set, you should be fine:
```
create table T (ID int not null)
go
create view V
as
select * fro... | Create table Goods1 with "insert trigger" on it which make insert into Goods and delete from Goods1 | SQL.Working with views | [
"",
"sql",
"sql-server",
"view",
"triggers",
""
] |
Guys I am trying to make a simple ticket generation system for my company as a favor. For now, I have a table called `tblTicket` and another table called `tblEngineer` in my MSSQL database.
My application is in C# windows forms, so on the new ticket generation form, I have many textboxes and a comboBox for assigning e... | Standard practice would be this, as an example...
You have a "tblEngineer" table...
```
tblEngineer
-----------
(PK) EngineerId
EngineerName
```
And a "tblTicket" table...
```
tblTicket
---------
(PK) TicketId
TicketDetails
```
You now add a link table called "tblEngineerTickets" (or similar) which referen... | I would suggest making 1-to-Many relationships instead of making many-to-many relationships. You can accomplish this by having a table that maps between your `tblTicket` and `tblEngineer`. For Example:
```
tblEngineer
-----------
(PK) iEngineerID
tblTicket
---------
(PK) iTicketID
tblTicketEngineerMap
------------... | Many to many relationship? | [
"",
"sql",
"many-to-many",
""
] |
I have a MySQL table named test. and I need to add three more columns `VERSION` datatype bigint, `CREATE_TIMESTAMP` datatype `Date` and `LAST_UPDATE_TIMESTAMP` datatype `Date`.
The default value for `VERSION` should be `0` and for `CREATE_TIMESTAMP` and `LAST_UPDATE_TIMESTAMP` it should be the current datetime.
Now I... | Use the **CURRENT\_TIMESTAMP** instead of **NOW()**:
```
ALTER TABLE masterdatabase.test add column CREATE_TIMESTAMP TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
``` | try this
```
alter table masterdatabase.test add column CREATE_TIMESTAMP datetime default NOW() ;
```
You need to store Date value in DATETIME as NOW() will retur you the date and time in format of *2008-11-11 12:45:34* and DATETIME can store this value for more detail see [this](https://dev.mysql.com/doc/refman/5.1/... | ALTER TABLE command to add columns in an existing Table with current date and time: Not Working | [
"",
"mysql",
"sql",
"date",
""
] |
How to get column values comma seperatedly in SQL Server. Below shown is my sql query#
```
select BandName from BandMaster where BandId<100
```
I need to get the BandName values comma seperatedly in a single query. | ```
Use XML path for this.
select (select BandName+',' from BandMaster where BandId<100 for xml path('')) as NewColumnName
Try this
``` | ```
Declare @retStr varchar(max) = ''
select @retStr = @retStr + BandName + ',' from BandMaster
where BandId<100
Select @retStr
``` | How to get column values comma seperatedly | [
"",
"sql",
"sql-server",
""
] |
Table `LESSON` has fields `LessonDate, MemberId` (Among others but only these two are relevant)
In English: Give me a list of the dates on which students that have only ever taken 1 class, took that class.
I have tried a number of things. Here's my latest attempt:
```
SELECT LessonDate
FROM LESSON
WHERE (SELECT CO... | The query may seem a little counter-intuitive at first. You need to group by `MemberId` to get the students who only took one class:
```
select max(l.LessonDate) as LessonDate
from Lesson l
group by l.MemberId
having count(*) = 1;
```
Because there is only one class for the student, `max(l.LessonDate)` is that date. ... | You need to look into `SELECT ... FROM ... GROUP BY ... HAVING` There is a lot of documentation available online by searching `GROUP BY` e.g. [This article](http://www.techonthenet.com/sql/group_by.php)
The following SQL groups by `MemberId` which I thnk is wrong as you want to count the number of member id's,
```
SE... | SELECT WHERE COUNT = 1 | [
"",
"sql",
"sql-server",
"subquery",
""
] |
Consider the following table :
```
create table mixedvalues (value varchar(50));
insert into mixedvalues values
('100'),
('ABC100'),
('200'),
('ABC200'),
('300'),
('ABC300'),
('400'),
('ABC400'),
('500'),
('ABC500');
```
How can I write a select statement that would only return the **numeric** values like
```
100
... | ```
SELECT *
FROM mixedvalues
WHERE value REGEXP '^[0-9]+$';
``` | ```
SELECT *
FROM mixedvalues
WHERE concat('',value * 1) = value;
```
Reference: [Detect if value is number in MySQL](https://stackoverflow.com/questions/5064977/detect-if-value-is-number-in-mysql) | MySQL - Select only numeric values from varchar column | [
"",
"mysql",
"sql",
"numeric",
"varchar",
""
] |
I have a table that contains a column showing whether an account is inactive.
The column values are either True or False... I
only want the False items.
So I've included a clause saying:
Where (account.inactive IN ("False"))
But I get a Operator/Operand type mismatch? error
I have been able to do other where clause... | I had a look at the data dictionary and it is logical type field with one character length. I tried a few different things and Where (account.inactive = 0) and it seems to work. | Are you sure the value can ever be 'FALSE'? Check the values available for filtering:
```
SELECT DISTINCT account.inactive
FROM ((((account
LEFT JOIN trans
ON account.uniqueid = trans.accountid AND account.ledgerno=1 AND trans.trantype NOT IN (8) )
LEFT JOIN period
ON trans.periodno = period.periodno)
LEFT JOIN us... | SQL WHERE Clause True or False values | [
"",
"sql",
""
] |
Having a table `TAB_A`:
```
ID | Date | Value
--------------------------------
101 | 2014-03-01 | 101000001
101 | 2014-03-03 | 101000003
101 | 2014-03-06 | 101000006
102 | 2014-03-01 | 102000001
103 | 2014-03-01 | 103000001
```
And, for example, this single record in another table `TAB_B`:
```... | Seeing as the tag is sql-server, `Limit` won't work. Instead, use top
```
SELECT TOP 1 ID, Date, Value
FROM TAB_A
WHERE Date < (SELECT Date from TAB_B where ID=40002)
ORDER BY Date DESC
```
or
```
SELECT ID, Date, Value
FROM tab_a
WHERE date=
(SELECT MAX(date)
FROM TAB_A
WHERE Date <
(SELECT... | ```
SELECT ID, Date, Value
FROM TAB_A
WHERE Date < (SELECT Date from TAB_B where ID=40002)
ORDER BY Date DESC LIMIT 1
```
First you select this date which you need from TAB\_B in a subquery. Then you select all these dates that are earlier than this from TAB\_B (you can modify to <= if you need). Then you order des... | SQL get the closest row for a certain date in other table | [
"",
"sql",
"sql-server",
""
] |
I want do this:
```
SELECT *
FROM (t1 NATURAL JOIN t2) AS H
.
.
.
```
But it makes this error: `SQL command not properly ended` in this line.
How I can make it if I can? | You code doesn't make any sense. What do you expect to be named as `H` here? Both tables? That's not possible. What if there are fields with the same name in both tables? `H.someField` could be ambiguous.
You can make an alias (do `AS something`) only for tables and fields - one alias per one table/field. But not to g... | You mean like this :
```
SELECT * FROM TABLE1 AS T1
INNER JOIN TABLE2 T2 ON T1.ID=T2.ID
``` | How to rename a table in SQL with join | [
"",
"sql",
""
] |
I have the following table structures for which I am trying to obtain a totals and subtotals and show a rollup of the values.
```
ChartOfAccounts(AccountNumber, AccountDescription, ParentAccountNumber, IsControlAccount)
Ledger(LedgerId, JournalId, AccountNumber, IsDebit, Amount)
```
I have managed to use CTE to obtai... | Here is what I came up with and was able to get really close to matching your desired output
```
WITH CTEAcc
AS
(
SELECT
coa.accountDescription,coa.accountnumber,coa.accountnumber as parentaccount
FROM ChartOfAccounts coa
where iscontrolaccount=1
union all select c.accountdescription, coa.acco... | Yet another variation. Kept the hierarchy and iscontrol fields in just for reference. First it associates the account hierarchy with each account (the recursive cte). Then, for each account, computes sums of the ledger items for the account based on the hierarchy position (and whether it is a control account or not). F... | Getting totals and sub-totals in Parent-Child hierarchy | [
"",
"sql",
"sql-server",
"parent-child",
"rollup",
""
] |
i have given the following question in assignment. i m not able to understand how to pass argument in stored procedure.
Quesiton :
`If n = 1, FibNum(a, b, n) = a`
`If n = 2, FibNum(a, b, n) = b`
`If n > 2, FibNum(a, b, n) = FibNum(a, b, n-1) + FibNum(a, b, n-2) a`.
Create a **recursive stored procedure FibNum in T-SQ... | Procedure
```
create proc FibNum ( @a int, @b int, @n int )
as begin
if @n = 1 return @a
if @n = 2 return @b
if @n > 2 begin
declare @n1 int = @n - 1, @n2 int = @n - 2, @R1 int, @R2 int
exec @R1 = FibNum @a,@b,@n1
exec @R2 = FibNum @a,@b,@n2
return @R1 + @R2
end
return 1
end
```
Utilization ... | This seems like a function problem, but not because of a recursive stored procedure. You can actually do this using a recursive CTE.
The natural way of doing this would be something like:
```
with fib as (
select 1 as i, 0 as n
union all
select 2 as i, 1 as n
union all
select f1.i + 1, f... | Create a recursive stored procedure in T-SQL to calculate the n-th Fibonacci number | [
"",
"sql",
"t-sql",
"sql-server-2012",
""
] |
```
CREATE TABLE "TEST"."AB_EMPLOYEE22"
( "NAME" VARCHAR2(20 BYTE),
"AGE" NUMBER,
"SALARY" NUMBER,
"DOB" DATE
)
alter table "TEST"."AB_EMPLOYEE22" add constraint
Age_check check((ROUND((sysdate-DOB)/365)) = AGE) ENABLE
```
But This query is not working.
Pls help me out | You cannot use SYSDATE in check constraint. According to Oracle Documentation - [**Check Constraint**](http://docs.oracle.com/cd/E11882_01/server.112/e41084/clauses002.htm#SQLRF52204)
> Conditions of check constraints cannot
> contain the following constructs:
>
> * Subqueries and scalar subquery expressions
> * Calls... | Disclaimer: *It's not a direct answer to the question.*
Now, don't store derived and most importantly constantly changing data such as `age` in the table. Instead calculate it on the fly when you query it (e.g. with a view).
```
CREATE TABLE ab_employee22
(
name VARCHAR2(20),
salary NUMBER,
dob DATE
);
CREA... | I am trying To add Check constraint for checking age and date of birth | [
"",
"sql",
"oracle",
""
] |
I have two tables `A(column1,column2)` and `B(column1,column2)`.
How to ensure that a value from A(column1) is not contained within B(column1) and insert it in this column.
My Query will be like this :
```
insert into B.column1 values()
where
...
```
I want to complete B.column1 with data from A.column1
What sh... | ```
Insert Into B(column1)
Select A.Column1
From A
Where A.Column1 not in (Select Column1 From B)
``` | I would use MINUS command and select all rows from A(column1) which are not in B(column1) and then SELECT INTO result into B table. | complete a table with data from an other one | [
"",
"sql",
"oracle9i",
""
] |
In a table with two nullable date/datetime columns, how would you efficiently select the earliest of both dates that's not NULL?
Concretely, this is what I'm interested in:
```
| Date1 | Date2 | | Expected |
|------------|------------| |------------|
| 2014-02-23 | 2014-01-16 | | 2014-01-16 |
| 2... | You have to check for NULLs, try this:
```
SELECT IF(Date1 IS NULL OR Date2 IS NULL,
COALESCE(DATE1, DATE2),
LEAST(DATE1, DATE2)
) AS EarlyDate
FROM MyTable
```
Working Fiddle: <http://sqlfiddle.com/#!2/7940c/1> | You can use LEAST on COALESCE(date1,date2) and COALESCE(date2,date1):
```
SELECT LEAST( COALESCE(Date1,Date2) , COALESCE(Date2,Date1) ) AS EarlyDate
FROM MyTable;
``` | Select earliest of two nullable datetimes | [
"",
"mysql",
"sql",
"datetime",
""
] |
I prepared [a **fiddle** which demonstrates the problem](http://sqlfiddle.com/#!15/e25c5/2).
```
CREATE TABLE parent (
parent_id integer primary key
);
CREATE TABLE child (
child_name TEXT primary key,
parent_id integer REFERENCES parent (parent_id) ON DELETE CASCADE
);
INSERT INTO parent VALUES (1);
INSERT... | Foreign keys only work in the other direction: cascade deletes from parent to child, so when the parent (referenced) record is deleted, any child (referencing) records are also deleted.
If it's a 1:1 relationship you can create a bi-directional foreign key relationship, where one side is `DEFERRABLE INITIALLY DEFERRED... | You seem to want to kill the whole family, without regard to remaining children. Run this instead of `DELETE FROM child ...`:
```
DELETE FROM parent p
USING child c
WHERE p.parent_id = c.parent_id
AND c.child_name = 'michael';
```
Then everything works with your current design. If you insist on your original `DE... | How to CASCADE a delete from a child table to the parent table? | [
"",
"sql",
"postgresql",
"database-design",
"foreign-keys",
"cascade",
""
] |
there is a `siteOrder` table where i am checking orders placed by sites in current week, two columns in question are `siteName` and `OrderDate`, i am only considering four sites and ignoring others.
But if there is no order placed for any of these four sites then i want `0` to be displayed against the site rather than... | ```
select SiteName
,SUM(Case When DATEPART(mm,OrderDate) = DATEPART(mm,getdate())
and DATEPART(yyyy,OrderDate) = DATEPART(yyyy,getdate())
and DATEPART(dd,OrderDate) > DATEPART(dd,DATEADD(DAY, 1-DATEPART(WEEKDAY, getdate()), getdate()))
Then 1
... | If you don't already have these values in another table, you can create four rows in a subquery and then use a `LEFT JOIN`:
```
SELECT SiteName,COUNT(SiteName) AS Completed
FROM (
select 'Site1' union all
select 'Site2' union all
select 'Site3' union all
select 'Site4'
) Sites (name)
LEFT JOIN
SiteOrder ON... | sql server insert missing record | [
"",
"sql",
"sql-server",
""
] |
I Have a query to count the records which are aged between 4 and 12 months in my table
```
SELECT count(*)
from tm_process_state
where tstamp BETWEEN ADD_MONTHS(trunc(SYSDATE,'MONTH'), -12)
AND LAST_DAY(TRUNC(SYSDATE, 'MONTH') - 4);
```
After running am getting count value as 1240, which is wron... | This condition:
```
where tstamp BETWEEN ADD_MONTHS(trunc(SYSDATE,'MONTH'), -12) AND LAST_DAY(TRUNC(SYSDATE, 'MONTH') - 4)
```
is calculating from the *beginning* for the months (due to the `TRUNC(SYSDATE, 'MONTH')`) to the end of a month Why not just do:
```
where tstamp BETWEEN ADD_MONTHS(SYSDATE, -12) AND ADD_MON... | you want use simply sum function
like this
```
SELECT SUM(case when transits.direction = 1 then 1 else 0 end) ,
SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t
where t.device in ('A','B') group by t.device
```
I do not know actual condion in your query so ...
```
SELECT
... | select count of records between 4 and 12 months | [
"",
"sql",
"oracle",
"select",
""
] |
Im creating a MySQL Schema with Two Tables (Student and Instructor).
```
1. Students are given a student number when they join the school.
This is stored along with their name, date of birth, and the date they joined
the school.
2. All instructors are also students, but clearly, not all students are
instruct... | I am not sure why you need `is_instructor` field in the student table. You will need to update it each time you add or remove a record from `instructor` table. If you need to see if particular student is an instructor a simple hash join on `student_id` would suffice. But the options I see: first is using a stored proce... | How about something in the lines of...
```
INSERT INTO INSTRUCTOR (STUDENT_ID, INSTR_STATUS, DATE_WORKED)
SELECT ID, 'volunteer', NOW()
FROM STUDENT
WHERE IS_INSTRUCTOR = 1
```
You might want to rethink your design. | MySQL Insert Query With Conditional Statement | [
"",
"mysql",
"sql",
"mysql-workbench",
""
] |
I am very much use to work with ORM (e.g. EF, L2S). So, finding difficulty writing queries.
I've created an `Employee` table also few masters like `Department`, `Area`.
Schema is something like:
* `Employee` (`Id, Name, DeptId, AreaId, ManagerId`)
* `Area` (`Id, Name`)
* `Department` (`Id, Name`)
Now, I want to add... | Try this:
```
ALTER TABLE EMPLOYEE ADD
CONSTRAINT [FK_EMPLOYEE_DEPARTMENT]
FOREIGN KEY (DEPTID) REFERENCES DEPARTMENT(ID),
CONSTRAINT [FK_EMPLOYEE_DEPARTMENT]
FOREIGN KEY (AREAID) REFERENCES AREA(ID),
CONSTRAINT [FK_EMPLOYEE_EMPLOYEE]
FOREIGN KEY (MANAGERID)... | You just need to separate each constraint with a comma, eg:
```
ALTER TABLE EMPLOYEE
ADD CONSTRAINT [FK_EMPLOYEE_DEPARTMENT] FOREIGN KEY (DEPTID) REFERENCES DEPARTMENT(ID),
CONSTRAINT [FK_EMPLOYEE_DEPARTMENT] FOREIGN KEY (AREAID) REFERENCES AREA(ID),
CONSTRAINT [FK_EMPLOYEE_EMPLOYEE] FOREIGN KEY (MANAGE... | SQL Server - Multiple foreign key constraint in one go | [
"",
"sql",
"sql-server",
""
] |
Let's say I have this table:
```
create table test3(
id INT NOT NULL AUTO_INCREMENT PRIMARY_KEY,
an int(4),
mois int(2),
jour int(2),
data varchar(255)
);
mysql> desc test3;
+-------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+----... | Ideally, don't store the data in that format. If you have the power to change it to a `DATE`, then do so! If not, then raise the concern to whomever stores the data that it is difficult, slow and error-prone to do data queries when the data is stored in an inappropriate manner.
Also point out to them that if they want... | If you must still have the three parts of the date seperate, you can use the following:
`CAST( CAST( an as varchar(4) ) + '-' + CAST( mois as varchar(2) ) + '-' + CAST( jour as varchar(2) ) as DATE )`
I would suggest adding this as part of a view on the table, e.g.
```
CREATE VIEW test3withDate AS
SELECT id, an, moi... | In MYSQL, how to filter a date interval by using 3 separated fields for the date? | [
"",
"mysql",
"sql",
"date",
""
] |
Good day!
i've got some problem with that query:
```
SELECT `id`
FROM `test`
WHERE `name`
LIKE "somename" AND `id` = (SELECT max(`id`) FROM test)
```
It returned an empty result.
But
```
SELECT `id`
FROM `test`
WHERE `name` LIKE "somename"
```
works.
Moreover,
```
SELECT `id`
FROM `test`
WHERE `id` = (SELECT max... | I think you are probably looking for something like this:
```
SELECT *
FROM
test
WHERE
id=(SELECT max(id) FROM test WHERE name LIKE "somename")
```
this will return the row from test that has the maximum ID where name is like "somename" | Because they would have to be both true at the same time.
Imagine the following
```
id name
1 'somename'
2 'someothername'
```
In the above case
```
SELECT `id`
FROM `test`
WHERE `name` LIKE "somename"
```
Will return the first row but:
```
SELECT id FROM test WHERE id = (SELECT max(id) FROM test)
```
... | Mysql `AND` operator | [
"",
"mysql",
"sql",
"pymysql",
""
] |
Im kind of stuck at a problem that looks simple. Can somebody please help me on this one?
The actual table has 25 columns.
But basically to form this question lets say it looks something like this:
```
SR | Type | Des | Code
-------------------------
1 | wo | abc | 100
-------------------------
2 | co ... | I've had a go at your query. The Sub Query in the FROM clause gets the grouping by CODE and determines what the min and max values are for SR. Once we have this we join back into the main table on CODE and the minSR\maxSR values to get the corresponding Type and Des values. This makes the assumption that every CODE wil... | Here is a solution using ANSI window functions:
```
select sr,
first_type as type,
last_des as des,
code
from (
select sr,
type,
des,
code,
first_value(type) over (partition by code order by sr rows between unbounded preceding and unbounded following) ... | Sql query to pick up values on some rules | [
"",
"sql",
"rank",
""
] |
I have a hive table with tweets about movies and a table with keywords mapped to movie titles
keyword example:
```
title keyword
------ -------
3 Days to Kill 3daystokill
3 Days to Kill 3 days to kill
12 Years a Slave 12YearsASlave
```
tweets example:
```
id ... | You are looking for `like`, not `=`:
```
SELECT k.keyword, t.text
FROM keywords k JOIN
tweets t
ON t.text like CONCAT('%', k.keyword, '%')
WHERE k.title = '3 Days to Kill';
```
EDIT:
I was not aware that HiveQL limited `like` to only wildcards at the beginning or end. One option is `rlike`. Another is `ins... | I am not sure if the below helps.. :( But have just given a try.
```
select case when
replace(keyword,' ',null) = '3daystokill'
then keyword
end
from keywords
``` | Hive query: Match string with list of keywords | [
"",
"sql",
"hive",
"hiveql",
""
] |
I captured request and response time for procedure i need to calculate time take by substract both request -response to find time taken.
```
P_REQUEST_TIME :='20/MAR/2014 03:03:50.785662 PM';
P_RESPONSE_TIME :='20/MAR/2014 03:03:50.785816 PM';
SELECT TO_TIMESTAMP(P_REQUEST_TIME)-TO_TIMESTAMP(P_RESPONSE_TIME)
i... | Use [EXTRACT](http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions050.htm) function.
```
SELECT EXTRACT(SECOND FROM TO_TIMESTAMP(P_REQUEST_TIME)-TO_TIMESTAMP(P_RESPONSE_TIME)) diff_seconds
FROM <table_name>;
``` | ```
select extract( day from diff ) days,
extract( hour from diff ) hours,
extract( minute from diff ) minutes,
extract( second from diff ) seconds
from (SELECT TO_TIMESTAMP(REQUEST_DTTM)-TO_TIMESTAMP(RESPONS_DTTM) diff FROM hit_tracer);
``` | timestamp having milliseconds convert to seconds in oracle | [
"",
"sql",
"oracle",
"plsql",
""
] |
I am trying to execute a query to fetch all students that belongs to a specific hostel,with hostel id, on SqlServer but facing the error *`Subquery returned more than 1 value.`* query is :
```
select * from students
where StudentID=(select studentID from Student_To_Hostel where hostelID=2)
```
How to fix it ??? | **Method 1:**
You need to use **[JOIN](http://www.techonthenet.com/sql/joins.php)** here
Try like this
```
SELECT S.*
From Students S Inner JOIN Student_To_Hostel SH ON
SH.StudentID =S.StudentID
WHERE SH.hostelID=2
```
**Method2:**
You can use **[IN](http://technet.microsoft.com/en-us/library/ms1776... | Try replacing the '=' sign in the outer query with 'in'.
```
select * from students
where StudentID in (select studentID from Student_To_Hostel where hostelID=2)
```
Hope it Helps
Vishad | Error : SubQuery returns more than one records | [
"",
"sql",
"sql-server",
"database",
""
] |
I have a varchar(5) field. I need find the first unused number across all records such that they begin with leading zeros. like if there is a 00001 and a 00003 I'd like the query to return 00002. Also, many of the records contain letters and look like 'G0542'. These can be ignored.
I know I'm close. This seems to work... | Here is a version of your query that works:
```
With usedNos as (
select CAST(case when isnumeric(b_addr.inst_no) = 1
then b_addr.inst_no
end AS INT) as inst
from b_addr
)
SELECT RIGHT('00000' + CONVERT(VARCHAR(5), COALESCE(min(inst)+1, 0)),5) AS next_inst... | You can check whether the number you're trying to cast is a real number:
Instead of
```
CAST(b_addr.inst_no AS INT) as inst
```
Do something like
```
CAST(CASE WHEN ISNUMERIC(b_addr.inst_no) = 1 THEN b_addr.inst_no ELSE 0 END AS INT) as inst
```
It's a bit convoluted, but it works.
**Demo: <http://sqlfiddle.com/#... | First unused number in a varchar(5) field padded with zeros | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have a query like
```
select SUM(*) as "tot1" from table1 t, table2 t2 where t1.id=t2.id and t1.column=1
select SUM(*) as "tot2" from table1 t, table2 t2 where t1.id=t2.id and t1.column=2
select SUM(*) as "tot3" from table1 t, table2 t2 where t1.id=t2.id and t1.column=3
```
I want a query result look like this
`... | try this:
```
select * from
(select SUM(*) as "tot1" from table1 t, table2 t2 where t1.id=t2.id and t1.column=1) a,
(select SUM(*) as "tot2" from table1 t, table2 t2 where t1.id=t2.id and t1.column=2) b,
(select SUM(*) as "tot3" from table1 t, table2 t2 where t1.id=t2.id and t1.column=3) c
``` | Try this query
```
select
SUM(CASE t1.column WHEN 1 THEN t1.column ELSE 0 END) as tot1,
SUM(CASE t1.column WHEN 2 THEN t1.column ELSE 0 END) as tot2,
SUM(CASE t1.column WHEN 3 THEN t1.column ELSE 0 END) as tot3
from
table1 t, table2 t2
where
t1.id=t2.id
``` | adding a new column SQL query | [
"",
"sql",
"postgresql",
""
] |
I'm currently running more database queries of update, like the following:
```
UPDATE table SET status = 1 WHERE id = 3
UPDATE table SET status = 1 WHERE id = 7
UPDATE table SET status = 1 WHERE id = 9
UPDATE table SET status = 1 WHERE id = 18
etc...
```
**Question:**
How is it possible to run these queries in one? | If you need to update some rows on a given list you can use [**`IN()`**](http://dev.mysql.com/doc/refman/5.0/en/any-in-some-subqueries.html)
```
UPDATE table SET status = 1 WHERE id IN (3, 7, 18);
```
If instead you need to update all rows just don't add any `WHERE` conditions
```
UPDATE table SET status = 1;
``` | ```
UPDATE table SET status = 1 WHERE id in (3,7,9,18,...)
``` | How to update multiple rows with one query with MySQL? | [
"",
"mysql",
"sql",
""
] |
My database has two tables, a car table and a wheel table.
I'm trying to find the number of wheels that meet a certain condition over a range of days, but some days are not included in the output.
Here is the query:
```
USE CarDB
SELECT MONTH(c.DateTime1) 'Month',
DAY(c.DateTime1) 'Day',
COUNT(w.ID) '... | You were on the right track with a `LEFT JOIN`
Try run your query with this kind of outer join but remove your `WHERE` clause. Notice anything?
What's happening is that the join is applied and then the where clause removes the values that don't match the criteria. All this happens before the group by, meaning the car... | You probably want to use a `LEFT OUTER JOIN`:
```
USE CarDB
SELECT MONTH (c.DateTime1) 'Month', DAY (c.DateTime1) 'Day', COUNT (w.ID) 'Wheels'
FROM tblCar c LEFT OUTER JOIN tblWheel w ON c.ID = w.CarID
WHERE c.DateTime1 BETWEEN '05/01/2013' AND '06/04/2013'
AND (w.Measurement IS NULL OR w.Measurement < 18)
GROUP BY... | Missing a single day | [
"",
"sql",
"sql-server",
""
] |
When I don't use `WHERE` clause query works fine. How can I make it work with `WHERE` clause? Is it too ambitious?
Thanks
**ERROR**:
```
[Err] 1054 - Unknown column 'claims.client_name' in 'where clause'
```
**SQL:**
```
SELECT
(
CASE
WHEN client = 'Driver' THEN (SELECT fullname FROM driver WHERE id = ... | Replace
```
WHERE (client_name LIKE '%john%')
```
with
```
HAVING (client_name LIKE '%john%')
``` | Try this :-
```
SELECT CASE WHEN client = 'Driver' THEN (SELECT fullname FROM driver WHERE id = claims.client_id)
WHEN client = 'Passenger' THEN (SELECT fullname FROM passengers WHERE id = claims.client_id)
WHEN client = 'Thirdparty' THEN (SELECT fullname FROM thirdparty WHERE id = claims.client_id)
... | WHERE clause to select from AS part of the query | [
"",
"mysql",
"sql",
""
] |
I have all the primary keys and drop tables in the correct order.
I basically want stockID to be a foreign key in my refund table.
My schema looks like this...
```
CREATE TABLE refunds (
refundID SMALLINT AUTO_INCREMENT,
stockID SMALLINT,
refundDate DATE,
FOREIGN KEY (stockID) REFERENCES tblStock(stockID),
PRIMARY K... | When referencing another table for a foreign key reference, that table needs to already exist. And, the column being referenced should be a primary key. Try this:
```
CREATE TABLE tblStock (
stockID SMALLINT AUTO_INCREMENT PRIMARY KEY,
stockName VARCHAR(60),
StockNumbers SMALLINT
);
CREATE TABLE refunds (
ref... | ```
FOREIGN KEY (stockID) REFERENCES tblStock(stockID)
```
Is referencing a table that doesn't yet exist. Create `tblStock` first. | #1005 - Cant create table... (errno: 150) | [
"",
"mysql",
"sql",
"errno",
""
] |
I have a table called
`A` and it contains column called `A1` and it has `A21, A31 , A41` as row values
**A** :
```
A1
+---+
A21
A31
A41
```
I have another table called `B` and it has columns of `A21,A31,A41`
**B:**
```
| A21 | A31 | A41
```
Now how can i make a inner join to find col... | Your question is a bit ambiguous, but this might be what you mean:
```
select *
from A1 a
inner join information_schema.columns c on c.column_name = a.A1
where c.table_name = 'B'
```
Although why you want this is a bit of a mystery! | Try this,
```
SELECT
A1.*
FROM
A1
INNER JOIN sys.columns S ON S.name = A1.name
INNER JOIN sys.tables ST ON ST.object_id = s.object_id
WHERE
ST.name = 'A2'
``` | How to Compare information schema column with Table Column in Sql Server2008 using inner Join? | [
"",
"sql",
"sql-server",
"sql-server-2008",
"c#-4.0",
""
] |
There is a sample schema in here:
<http://sqlfiddle.com/#!2/c0723a/2>
query is `select id,group_concat(val) from test group by id`
result is
> ID GROUP\_CONCAT(VAL)
> 1 ,64,66,,203,214,204
I wanted to concat val field without a comma for empty records like this
> ID GROUP\_CONCAT(VAL)
> 1 64,66,203,214,204 | Simply use **Replace**
```
select id,replace(group_concat(val),',,',',') from test group by id
```
Or you can use **IF**
```
select id,group_concat(if(val ='',null, val)) from test group by id
```
Or You can use **NULLIF**
```
select id,group_concat(Nullif(val,'')) from test group by id
```
**[Fiddle Demo](http:/... | ```
SELECT id, GROUP_CONCAT(val) FROM test
WHERE val is not null AND val <> ''
GROUP BY id
``` | Mysql group_concat adds a separator for empty fields | [
"",
"mysql",
"sql",
"group-concat",
""
] |
i know this must be in SQL 101, but i need to return rows where a column contains both X And Y, where an ID is duplicated.
Example Table.
```
ACCOUNT | Activity
-------------------------
1 | Email
1 | Appointment
2 | Email
2 | Email
3 | Email
3 | ... | Here's one way to do it. Use an `EXISTS` predicate that uses a correlated subquery to check for the existence of the "other" row. This assumes that you only want to return rows that have values of 'Email' and 'Appointment' in the Activity column, and to exclude rows that have any other value for activity. (This isn't t... | A very naive approach would be:
```
SELECT
*
FROM MyTable t1
WHERE EXISTS
(
SELECT 1 FROM MyTable WHERE ACCOUNT = t1.ACCOUNT AND Activity = 'Email'
)
AND EXISTS
(
SELECT 1 FROM MyTable WHERE ACCOUNT = t1.ACCOUNT AND Activity = 'Appointment'
)
``` | SQL Return rows where column 1 contains X and Y | [
"",
"mysql",
"sql",
"return",
"duplicates",
""
] |
Since `EXCEPT` is a Set Operation, it automatically makes its results distinct. How can I rewrite a query like the following without the result containing only distinct values?
```
SELECT T1.ContainerName, T1.PanelName FROM MyTable AS T1
EXCEPT
SELECT T2.ContainerName, T2.PanelName FROM MyOtherTable AS T2
```
Given t... | You appear to want everything from `mytable` where there is no corresponding row in `myothertable`. Sounds like a job for `exists()`. Try:-
```
select t1.ContainerName, t1.PanelName
from MyTable t1
where not exists(
select * FROM MyOtherTable t2
where t2.ContainerName=t1.ContainerName
and t2.PanelName=... | how about `LEFT JOIN`
```
SELECT t1.*
FROM MyTable1 AS t1
LEFT JOIN MyTable2 AS t2
ON t1.ContainerName = t2.ContainerName
AND t1.PanelName = t2.PanelName
WHERE t2.PanelName IS NULL
```
* [SQLFiddle Demo](http://sqlfiddle.com/#!2/58c1ca/1) | Rewrite Except Without Distinct | [
"",
"sql",
"t-sql",
""
] |
I'm trying to make an optimal SQL query for an iSeries database table that can contain millions of rows (perhaps up to 3 million per month). The only key I have for each row is its RRN (relative record number, which is the physical record number for the row).
My goal is to join the table with another small table to gi... | I find it hard to believe that querying a table of mere 3 million rows, even when joined with something else, should cause an out-of-memory condition, so in my view you should address this issue first (or cause it to be addressed).
As for your question of *why the RRNs end up different* I'll take the liberty of quotin... | Trying to use RRN as a primary key is asking for trouble.
I find it hard to believe there isn't a key available.
Granted, there may be no explicit primary key defined in the table itself. But is there a unique key defined in the table?
It's possible there's no keys defined in the table itself ( a practice that is 20... | iSeries query changes selected RRN of subquery result rows | [
"",
"sql",
"db2",
"ibm-midrange",
"db2-400",
""
] |
I am trying to make an application, and it requires me to store the data somewhere. so i have to create a database and i have absolutely no idea about making database. i can make the android application for for the front end but i need help with storing, retrieving and manipulating the data stored online.
1. How and w... | Not sure if you're asking how to create and use a database in Android, or online, so I'll try to answer both.
SQlite is the default embedded database solution in Android. You have two options here, but I'll go ahead and advise you to choose the former.
First option is to do it, as they say, "close to the metal" as po... | I guess you will have to follow the client - server protocol.
1. Use SQLite Database (relational database) on the client (Android) to store data locally.
2. On your server, get a Relational Database eg. On Amazon EC2 you can get one.
3. Create an API for your application on the server, which will accept HTTP requests ... | Database for android online | [
"",
"android",
"sql",
"database",
""
] |
Hi i'm a beginner in Ruby on Rails
Here is my doubt.
I have this method in my controller
```
def save_profile
p "======================================"
p params
p "======================================"
p params[:company][:job_locations_attributes]
p "company_params------------------------"
p... | If you'd like to keep it short
```
job_id, state_id = params[:company][:job_locations_attributes].first
Location.create(:job_id => job_id, state_id => state_id.values[0])
``` | you can use it.
```
job_id = params[:company][:job_locations_attributes].keys[0]
state_id = params[:company][:job_locations_attributes][job_id]['job_locations']
``` | Ruby on Rails Saving to Database | [
"",
"sql",
"ruby-on-rails",
"ruby",
""
] |
I have lots of useless approved comments on my site. One way I use of removing them is
```
DELETE FROM wp_comments WHERE comment_content LIKE '%agree%with%you,%thanks%, '
```
However, this is removing good comments as well and leaving out a lot of bad comments.
How Do I modify the query to delete comments with less ... | try using `LENGTH` . bellow you will delete entries which have less then 35 characters. Ithink its better then using words.
```
length(comment_content) < 35 --//change length number as you want //35 characters
```
like that:
```
DELETE FROM wp_comments WHERE comment_content LIKE '%agree%with%you,%thanks%, '
... | The most effective way is:
**MySQL Query Start:**
**`-- Select All Rows`**
```
mysql> SELECT * FROM comments;
+----+---------------------------------------------------------------------------------------------------------------+---------------------+
| id | comments ... | Delete Comments / Content with Less than 5 words | [
"",
"mysql",
"sql",
"wordpress",
"phpmyadmin",
""
] |
I have this Application where Releasedates of Musicalbums are saved into the MySQL Database as `Varchar` (I have no influence on that) so it displays the date like **(2014-09-11)**. How can I make it that the Releasedate gets displayed like only **(2014)** ? Do I have to convert it to `DATETIME`
My MySQl query looks l... | ```
SUBSTR(physicalReleaseDate, 1, 4)
SUBSTR(digitalReleaseDate, 1, 4)
``` | Try This...Use Year function of mysql for ref. <http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_year>
```
SELECT products.pro_id,products.title AS album_title, products.genre AS album_genre, products.coverarttoenailurl AS cover_image, products.ccws_pro_id
AS product_upc, t... | MYSQL Datetime as varchar and how to display year only | [
"",
"mysql",
"sql",
"datetime",
""
] |
I have to datetimeoffset fields, which I want to calculate the time between then.
I have done this:
```
CONVERT(varchar(5), DATEADD(MINUTE,DATEDIFF(MINUTE, P.DT_INIC_PARD , P.DT_TMNO_PARD ),0),114) AS 'Duration'.
```
The problem is: When the time between then is higher than 24 hours, the result query shows me '00:00... | What do you intend to do with that `DATEADD()` function? What it's doing is turning your `DATEDIFF()` output into a `DATETIME` field, which you then `CONVERT()` to a time format. You can't display more than 24 hours in a time format `00:00`, so you need to choose a different way to display the output.
This works fine:... | You can do the following:
```
SELECT CAST(Duration/60 AS VARCHAR(5)) + ':' +
RIGHT('0'+ CAST(Duration % 60 AS VARCHAR(2)),2)
FROM ( SELECT DATEDIFF(MINUTE, P.DT_INIC_PARD, P.DT_TMNO_PARD) Duration
FROM YourTable) A
``` | Datediff more than 24 hours | [
"",
"sql",
""
] |
I have a string something like this `1234-56-7-8-9012`. This can be any size and the values between the `-` can be any size. I need to extract the `7` in the middle of this string but cannot accommodate to the changing size of the string. This is what I've been using but it doesn't take the change of size:
```
@String... | Try this:
```
declare @String varchar(50) = '1234-56-7-8-9012'
select substring(@String, charindex('-',@String,charindex('-',@String,1)+1)+1,
charindex('-',@String,charindex('-',@String,charindex('-',@String,1)+1)+1)-
charindex('-',@String,charindex('-',@String,1)+1)-1)
``` | Please try:
```
declare @String nvarchar(1000) = '1234-56-72-9012'
select
LEFT(y, CHARINDEX('-', y)-1)
from(
select
RIGHT(x, LEN(x)-CHARINDEX('-', x)) y
from(
select RIGHT(@String, LEN(@String)-CHARINDEX('-', @String)) x
)x1
)x2
``` | Retrieve a string between 2 same variables SQL | [
"",
"sql",
"sql-server",
"substring",
"charindex",
""
] |
I'm trying to create a procedure that will insert me an new entry IF the ID is not already used. I just can't figure out what I'm not doing right there:
```
CREATE OR REPLACE PROCEDURE add_user
IS
BEGIN
IF NOT EXISTS SELECT * FROM tab WHERE tab.id = '111'
THEN
INSERT INTO tab(id, name, job, city, phone)
... | Do not try to enforce referential integrity in code as it is very, very likely that it will be very, very wrong. Not *obviously* wrong - no, this is the kind of "wrong" that only shows up when you have 200 users banging on the database and then something goes very very far south in a very big hurry and all of a sudden ... | The direct answer to your question is to put the subquery in parentheses:
```
IF NOT EXISTS (SELECT * FROM tab WHERE tab.id = 111) THEN
INSERT INTO tab(id, name, job, city, phone)
VALUES(111, 'Frank', 'Programmer', 'Chicago', '111111111');
END IF;
```
However, that is not a good solution to your problem (... | Using "IF NOT EXIST" in a procedure | [
"",
"sql",
"plsql",
""
] |
I'm trying to make a `Insert Select` query with additional parameters but it doesn't work. Below is my code:
```
INSERT INTO [epmscdc].[dbo].[billing]
([pid] ,[did] ,[lid] ,[totalamt] ,
[cash] ,[bchange] ,[btrans_date])
SELECT patientlab.did, patientlab.pid,
patientlab.lid, laboratory.lprice
FROM patientlab
... | ```
INSERT INTO [epmscdc].[dbo].[billing] ([pid] ,[did] ,[lid] ,[totalamt] ,[cash] ,[bchange] ,[btrans_date])
SELECT patientlab.did, patientlab.pid, patientlab.lid, laboratory.lprice , 1000,1000,GETDATE()
FROM patientlab
INNER JOIN laboratory ON patientlab.lid = laboratory.lid
INNER JOIN doctor ON patientlab.did = doct... | ```
INSERT INTO [epmscdc].[dbo].[billing] ([pid] ,[did] ,[lid] ,[totalamt] ,[cash] ,[bchange] ,[btrans_date]) VALUES
(SELECT patientlab.did, patientlab.pid, patientlab.lid, laboratory.lprice,1000,1000,GETDATE()
FROM patientlab
INNER JOIN laboratory ON patientlab.lid = laboratory.lid
... | Insert Select with additional parameters in SQL Server | [
"",
"sql",
"sql-server",
"insert-select",
""
] |
I have a large dataset with invoices that I need to perform some currency conversions on. There are a lot of *joins* required to get the data, but the basic idea is that One table has the individual invoice charges in USD, while another has the total charges in Local Currency, but no where are the individual charges on... | Don't think in terms of individual rows. You have sets of rows so think in terms of sets of each question. Using CTEs you can encapsulate each piece (result set for each part of the question) and combine the answers in either other CTEs or the final query.
The following adaptation of your query shows 3 CTEs:
1. First... | You must not approach it as a procedural program. SQL is a language for set manipulation. You need to think in terms like calculated columns and joins. First you need to calculate USD totals by invoice, then join it to LocalInvoiceTable and divide by ChargeTotal to get the FX rate. Finally join back to InvoiceTable and... | SQL Server to calculate a variable for every row in a query | [
"",
"sql",
"sql-server-2008",
"variables",
"local-variables",
""
] |
**EDIT**
After removing my silly mistake of `INTO` (I was working with INSERTS and just keep going) the error below is showing. Still not working:
> Affected rows: 0
>
> [Err] 1093 - You can't specify target table 'tbl'
> for update in FROM clause
---
I'm trying to create an update where I select all the previous d... | Do you need the sub query?
```
UPDATE tbl
SET string_id = CONCAT(string_id, ',13,14,15,16')
WHERE id = @id;
```
Note that in MySQL you cannot modify using an UPDATE the table that is used in the sub query (although there are fiddles around it):-
<https://dev.mysql.com/doc/refman/5.5/en/subqueries.html>
> *In MySQL... | Try to use `UPDATE` without `INTO`:
```
set @id = 3;
UPDATE tbl
SET string_id =
CONCAT((
SELECT tbl_alias.string_id
FROM tbl as tbl_alias
WHERE id = @id
),',13,14,15,16') WHERE id = @id;
```
**Update:**
Try this:
```
set @id = 3;
UPDATE tbl
SET string_id =
CONCAT(SELECT st... | Update mysql field using CONCAT and SELECT | [
"",
"mysql",
"sql",
"concatenation",
""
] |
I want to set a column in the `group by` table based on the first (actually, only) value in the group.
Specifically, given a table
```
id good
1 t
1 t
2 f
3 t
```
I want to produce the table
```
id multiplicity goodN
1 2 0
2 1 0
3 1 1
```
where `goo... | If the count is 1, then both the MAX(good) and MIN(good) will be the "first" row in the group.
```
select id, count(*) as multiplicity,
if (count(*) > 1, 0, if(max(good) = 't', 1, 0)) as goodN
from ...
``` | Select good from...
Where id=(select min(id) from...
Where good >0)
And
Group by id having count(id)=1
You can test count(goods) instead of count(\*) and at the end add group by id. To take only record with moltiplicity 1 add having count(goods)=1 | first value in group by | [
"",
"sql",
"hiveql",
""
] |
I have a query that I'm working with in Access that is supposed to take records specified in another query and alter them. Unfortunately, if I had multiple records selected before, it creates duplicates in this new query.
For example, if I had 2 records selected, it creates two of the same entry for each. If I had 3 s... | This is just a guess--but it looks like you have duplicate rows with the same ID in either `GV_transfer` or `GV_transfer3` or both. You will need to ensure that both tables use unique IDs. One way to check is to run the following query on the tables, one by one:
```
select ID, count(ID) as num_times
from GV_transfer
g... | You could try using the DISTINCT command. using SQL in access.
It will eliminate duplication in a column/columns.
Make a new query and select the current query you made that gave you the duplication.
SELECT DISTINCT("name of column")
FROM "name of table/query";
That will make a new query eliminating all duplication.
... | Access query returning duplicate records | [
"",
"sql",
"ms-access",
"join",
""
] |
I'm trying understand how I can pull information from multiple tables at once in one query if that is possible.
I have 3 tables and I'm wondering if there is a way I can query all the product names for customers that live in california?
```
Table:
products
Fields:
productOid
productName
companyOid
... | You will need to use inner joins for this.
```
SELECT DISTINCT p.productName
FROM orders o
INNER JOIN customerData c ON o.customerOid = c.customerOid
INNER JOIN products p ON o.productOid = p.productOid
WHERE c.state = 'CA';
```
I am using DISTINCT here because it's possible a customer would order the same product mo... | You could use one more join, but I would write it this way:
```
SELECT DISTINCT p.productName
FROM
orders o INNER JOIN products p
ON o.productOid = p.productOid
WHERE
o.customerOid IN (SELECT customerOid
FROM customerData
WHERE state = 'California')
```
It might be a litt... | Query for multiple tables | [
"",
"mysql",
"sql",
""
] |
I'm trying to insert new rows into my DB. I have 155 rows that I need to insert. What is happening is that I am adding new users based on an existing account table. I have a query that lists the new users that I need to add to the users table, but I don't want to have to type out the insert 155 times. Is there an easie... | Try this:
```
INSERT INTO tblUsers (State,City,Code)
SELECT 'IN','Indy', UserCode
FROM tblAccounts
WHERE UserCode IN
(SELECT UserCode
FROM tblAccounts
WHERE State = 'IN')
```
or better simplified (a subquery is not needed):
```
INSERT INTO tblUsers (State,City,Code)
SELECT 'IN','Indy', UserCode
FROM tb... | ```
insert into tblUsers (State,City,Code)
Select 'IN','Indy', UserCode
from tblAccounts
where UserCode in (Select UserCode
from tblAccounts
where State = 'IN')
``` | How to insert multiple rows with one insert statement | [
"",
"sql",
"sql-server-2008",
""
] |
I am trying to get the avg difference between order requested delivery date and actual delivery date, by Destination. The below is giving me issues. Do you know where I am going wrong? The message I am getting is "Each GROUP BY expression must contain at least on column that is not an outer reference"
```
SELECT CONCA... | There are several ways to improve your query. I would suggest:
```
SELECT CONCAT(l.City, ', ', l.State) AS Destination,
AVG(DATEDIFF(Day, o.ReqDate, o.SchedDate)*1.0) AS "Average Diff"
FROM dbo.Orders o join
dbo.Locations l
ON o.OrderNum = l.OrderNum
GROUP BY CONCAT(l.City, ', ', l.State) ;
```
Note ... | Try
```
SELECT CONCAT(Locations.City, ', ', Locations.State) AS Destination,
AVG(DATEDIFF("Day", Orders.ReqDate, Orders.SchedDate)) AS "Average Diff"
FROM dbo.Orders,
dbo.Locations
WHERE dbo.Orders.OrderNum= dbo.Locations.OrderNum
GROUP BY CONCAT(Locations.City, ', ', Locations.State)
``` | GROUP BY not working in my code | [
"",
"sql",
""
] |
Is it possible to `SELECT` name and address attribute from names table but at the same time I also want to combine description attribute from info table.
```
CREATE TABLE names(
ID CHAR(2) PRIMARY KEY
name VARCHAR2(20) NOT NULL
address VARCHAR2(40) NOT NULL
)
CREATE TABLE info (
ID CHAR(2) REFERENCES names
description... | ```
SELECT name, address, description
FROM names JOIN info USING(id)
``` | select n.name, n.address, i.description from names as n
Left join info as i on n.id = i.id | SELECT in SQL QUERY - is it possible | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I am trying to insert data into an existing table and keep receiving an error.
```
INSERT INTO Patient
(
PatientNo,
PatientFirstName,
PatientLastName,
PatientStreetAddress,
PatientTown,
PatientCounty,
PatientPostcode,
DOB,
Gender,
PatientHomeTelephoneNumber,
PatientMobileTelephoneNumber
)
VALUE... | Try replacing the string literal for date `'1989-12-09'` with `TO_DATE('1989-12-09','YYYY-MM-DD')` | The format you use for the date doesn't match to Oracle's default date format.
A default installation of Oracle Database sets the DEFAULT DATE FORMAT to `dd-MMM-yyyy`.
Either use the function `TO_DATE(dateStr, formatStr)` or simply use `dd-MMM-yyyy` date format model. | SQL Error: ORA-01861: literal does not match format string 01861 | [
"",
"sql",
"oracle",
"sql-insert",
""
] |
I am new to SQL and a little embarrassed to ask this.
I have A table that contains 2 columns A and B
```
A B
0 2
1 3
3 1
```
I want a query that will return
```
Category | Sum
A 4
B 6
```
What is the best way to write this query? | ```
select 'A', sum(A) from table
union
select 'B', sum(B) from table
``` | If UNPIVOT is supported by the SQL product you are using:
```
SELECT Category, SUM(Value) AS Sum
FROM atable
UNPIVOT (Value FOR Category IN (A, B)) u
GROUP BY Category
;
```
In particular, the above syntax works in [Oracle](http://sqlfiddle.com/#!4/f4b4f2/1 "Demo at SQL Fiddle") and [SQL Server](http://sqlfiddle.com/... | SQL counting values and selecting Column Name as result | [
"",
"sql",
""
] |
I have an SQL query that brings back 17 numbers with this format
> 06037-11
I need to add a 0 before the dash, so it is:
> 060370-11
Is there an easy way to do this? I have seen STUFF() as an option, but I don't understand it.
**Edit**
I am using Teradata | Previous response includes example for Teradata 14.x using regular expression support. The following will work in Teradata 13.x or Teradata 12.x without regular expression support:
```
SELECT SUBSTRING('06037-11' FROM 1 FOR (POSITION('-' IN '06037-11') -1))
|| '0-'
|| SUBSTRING('06037-11' FROM (POSITION('-' IN... | One way in Oracle:
```
with qry as
(select '06037-11' code from dual)
select regexp_replace(code, '-', '0-') from qry;
``` | SQL Adding the same char into multiple fields | [
"",
"sql",
"teradata",
""
] |
This seems like it should be easy, but isn't. I'm migrating a query from MySQL to Redshift of the form:
```
INSERT INTO table
(...)
VALUES
(...)
ON DUPLICATE KEY UPDATE
value = MIN(value, VALUES(value))
```
For primary keys we're inserting that aren't already in the table, those are just inserted. For primary keys ... | I'm having to do exactly this for a project right now. The method I'm using involves 3 steps:
**1.**
Run an update that addresses changed fields (I'm updating whether or not the fields have changed, but you can certainly qualify that):
```
update table1 set col1=s.col1, col2=s.col2,...
from table1 t
join stagetable... | Is posible to create a temp table. In redshift is better to delete and insert the record.
Check this doc
<http://docs.aws.amazon.com/redshift/latest/dg/merge-replacing-existing-rows.html> | Bulk updating existing rows in Redshift | [
"",
"sql",
"postgresql",
"amazon-redshift",
""
] |
```
TableOne
PersonId PersonScore
1 10
1 20
2 99
2 40
3 45
```
I need to fetch only those rows where PersonId appears More than Once e.g. Following is the resultset i want to achieve... | You want to use `count(*)` as a window function, rather than `row_number()`:
```
select t.PersonId, t.PersonScore
from (select t.*, count(*) over (partition by PersonId) as cnt
from TableOne t
) t
where cnt > 1;
``` | ```
SELECT *
FROM TableOne t1
JOIN (SELECT PersonId
FROM TableOne
GROUP BY PersonId
HAVING COUNT(*) > 1) t2
on t1.PersonId = t2.PersonId
``` | Select Rows that appear more than once | [
"",
"sql",
"sql-server",
""
] |
I am using Microsoft Access and am having difficulty with this scenario for two reasons:
1. the ORDER BY function is not working
2. When I run the query, a pop up box appears asking for a value to be entered for SalesOrder.PID. When I enter a 1, the datasheet appears.
Any advice would be much appreciated regarding my... | The pop-up box appears because `SalesOrder.PID` references a table `SalesOrder` that is not in the `from` clause. Presumably you mean `SalesOrderProduct`.
You should also use explicit joins in your query, and table aliases for *all* columns:
```
SELECT p.PID, p.Code, COUNT(sop.PID) AS Ordered,
SUM(sop.Extended... | If a pop up box appears asking for the SalesOrder.PID value this means Access doesn't recognise that column anywhere in the tables you've included in the query. In other words you are not counting SalesOrder.PID as Access doesn't recognise this. I would recommend checking your column names to make sure they are correct... | SQL Order By function not working | [
"",
"sql",
"ms-access",
"sql-order-by",
""
] |
This is sample table data. My Database consists of so many tables like this. In all the tables where wv1 is same and rv1 is different
```
wv1 rv1
341.6 2.48
343.6 2.58
344.7 2.37
346.3 2.32
347.9 2.29
349.5 2.36
351.1 2.23
352.6 2.24
354.2 ... | It is made through JSP + PostgreSQL
```
String ss1 = "SELECT UPPER(table_name)FROM information_schema.tables where table_schema='public' and table_type='BASE TABLE' ORDER BY table_name ASC;";
stmt = connection.createStatement();
rset=stmt.executeQuery(ss1);
```
The String ss1 is passed as dbTab
```
String usTab ="oa... | If I understand this correctly, you actually want to compare different sets that all 'look alike' (that is 2 columns, same number of rows, identical wv1 values) and each set is stored in a new table, right ?
My first remark would be: why didn't you store all the sets in the same table and add an extra column (eg. set\... | Compare one table with all tables in database | [
"",
"sql",
"postgresql",
""
] |
I have a table structure where there are `CARS` going between `BUILDINGS` that are built on `PLOTS`:
**CARS**
```
CAR_ID | ORIGIN | DESTINATION
----------------------------------
1 | A | C
2 | B | A
3 | A | B
```
**BUILDINGS**
```
BUILD_ID | PLOT
----... | below is my first thought:
```
select c.car_id,p1.coord as origin_coord, p2.coord as dest_coord
from cars as c
join buildings as b1 on b1.build_id=c.origin
join buildings as b2 on b2.build_id=c.destination
join plots as p1 on p1.plot_id=b1.plot
join plots as p2 on p2.plot_id=b2.plot
``` | Try
`SELECT C.car_id, po.coord as origin_coord, pd.cooord as dest_coord
FROM Cars as C
JOIN Buildings as o
on c.origin = o.build_id
JOIN Buildings as d
on c.destination = d.build_id
JOIN Plots as po
on po.plot_id = o.plot
JOIN Plots as pd
on pd.plot_id = d.plot
ORDER BY C.car_id` | SQL looking up values on three joined tables | [
"",
"sql",
"sql-server",
"join",
"lookup-tables",
""
] |
I have a query being executed every X milliseconds. As a part of result I would like to have alternating `true/false` flag. This flag should change whenever the query is executed again.
Example
Sample query: `select 1, <<boolean alternator>>;`
1st execution returns: `1 | true`
2nd execution returns: `1 | false`
3r... | I suggest a dedicated [**`SEQUENCE`**](http://www.postgresql.org/docs/current/interactive/sql-createsequence.html).
```
CREATE SEQUENCE tf_seq MINVALUE 0 MAXVALUE 1 START 0 CYCLE;
```
Each call with [`nextval()`](http://www.postgresql.org/docs/current/interactive/functions-sequence.html) returns 0 / 1 alternating. Yo... | A temporary table can save the boolean state:
```
create temporary table t (b boolean);
insert into t (b) values (true);
with u as (
update t
set b = not b
returning b
)
select 1, b
from t;
``` | Alternating true/false flag for current time given step | [
"",
"sql",
"postgresql",
"auto-increment",
"sql-insert",
""
] |
How can I get the output for maximum count of repeated values from a table, which contains the repeated values corresponding to a column such a way that there are multiple different distinct values having maximum-counts.
Consider r the table data below :
```
+---------+------------+-------------+--------------+
| Bil... | So, with some guessing, would
```
select
distinct g.customer_id,
g.cnt
from
(
select
distinct customer_id,
count(customer_id) cnt
from
table
group by
customer_id
) g
inner join
(
select
max(s.cnt) max_cnt
from
(
select
... | Just use multiple steps.
First save the count for every customer\_id. Then select the customer\_ids which have the MAX count.
```
CREATE TEMPORARY TABLE `tmp_count` SELECT count(*) as noOf, customer_id FROM `table` GROUP BY customer_id;
SELECT noOf, customer_id FROM `tmp_count` WHERE noOf = (SELECT MAX(noOf) FROM `tm... | To get the multiple maximum-count of repeated values in mysql | [
"",
"mysql",
"sql",
"groupwise-maximum",
""
] |
I need to do a correlated SQL Query and for that purpose i need to provide an alias to outer query which in which I perform an inner join. I am not able to do the alias
```
SELECT DISTINCT(name)
FROM PERSON
INNER JOIN M_DIRECTOR AS dira
ON (dira.PID = M_DIRECTOR.PID) as dira
WHERE 9 > (
... | I didn't really understand what you want to do, but I guess
```
select
distinct p.name,
count(d.MID) cnt
from
hindi2_PERSON p
inner join
hindi2_M_DIRECTOR d
on
p.PID = d.PID
group by
p.name
having count(d.MID) > 9
;
```
would do what you want | I dont know what you are asking and what you mean by make an alias to an eniter result ?
but you are doing
```
select distinct(name) as othername
```
which is you are selecting `name` and you are giving here `othername` as an alias
then you retrieve it in result
```
$row['othername']
``` | How to give alias to results returned after inner join in mySQL | [
"",
"mysql",
"sql",
""
] |
I am stuck on a project design. One of the table has 1-M relation with users table. So it has a foreign key. Same field is also primary key.
Table as follows
Itemid:
* Primarykey
* Autoincrement
Useriditem:
* Primarykey
* Foreign key of id in users table
Itemname:
* Not null
Values:
```
-----------------------... | You want something like this:
[Demo](http://sqlfiddle.com/#!2/8bd40e/1)
```
CREATE TRIGGER item_id_auto_inc
BEFORE INSERT ON items
FOR EACH ROW
BEGIN
SET NEW.item_id := (SELECT CASE WHEN ISNULL(MAX(item_id)) THEN 0 ELSE MAX(item_id) END +1 FROM items WHERE user_id=NEW.user_id);
END
//
``` | The safer way to do this is taking into account that your application can get hit by more than 1 user at any given time
```
START TRANSACTION;
Insert into table A
Select Last inserted id from table A using Last_Insert_ID()
Update table B
COMMIT;
```
At least you are guaranteed to get this last inserted id from tab... | Mysql->autoincrementing related to an other field | [
"",
"mysql",
"sql",
"auto-increment",
"ddl",
""
] |
I've got a boring issue to solve (hope it is hard only for me haha), as follows:
I have a PostgreSQL database with many tables.
These tables are updated daily by a Perl Script.
The table that interests for my problem follows the pattern below:
```
ID | Central | ts | Country | Name | Column3 | Col... | I've came to an answer with a LEFT JOIN, which includes every case I wanted.
Thanks a lot for every piece of advice, and sorry for not accepting any of the answers that came before mine...
Maybe I have not been fully clear, but my answer brings up the exact response to my problem.
I won't change the query to fit the ... | The way I would go about this would be with a self-join:
```
SELECT t.*
FROM theTable AS m -- values from the "master" central
INNER JOIN theTable AS t -- values from the central to test
ON m.Central = 'ALFA'
AND m.ts = (SELECT MAX(ts) FROM theTable)
AND m.ID = t.ID
AND m.ts = t.ts
AND t.Central... | Postgres LEFT JOIN and data manipulation | [
"",
"sql",
"postgresql",
""
] |
I wrote a program to generate tests composed of a combination of questions taken from a large pool of questions. There were a number of criteria for each test and the program saved them to database only if they satisfied these criteria.
My program was written to ensure as even a distribution of questions as possible, ... | You just need a `group by` to your first query (basically). I also added another condition, so the test ids are produced in order:
```
SELECT tq1.test_id as test_id1, tq2.test_id as test_id2, count(tq1.question_id) AS Overlap
FROM test_questions tq1 LEFT JOIN
test_questions tq2
ON tq1.question_id = tq2.quest... | I modified Gordon's answer and this query provides a listing of test combinations along with their corresponding overlap (questions in common):
```
SELECT tq1.test_id as test_id1, tq2.test_id as test_id2, count(tq1.question_id) AS Overlap
FROM test_questions tq1
JOIN test_questions tq2
ON tq1.question_id = tq2.questio... | Query to check for commonality (Intersection) between each possible pair combination | [
"",
"mysql",
"sql",
"combinations",
"set-intersection",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.