Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm using MySQL 5.5 so that's why I can't use FULLTEXT search so please don't suggest it.
What I wanted to do is if user I have 5 records for example :
```
Amitesh
Ami
Amit
Abhi
Arun
```
and if someone searches for Ami then it should returns Ami first as exact match then Amit & Amitesh | You can do:
```
select *
from table t
where col like '%Ami%'
order by (col = 'Ami') desc, length(col);
``` | ```
SELECT *
FROM table t
WHERE col LIKE '%Ami%'
ORDER BY INSTR(col,'Ami') asc, col asc;
``` | How to use MySQL like with order by exact match first | [
"",
"mysql",
"sql",
""
] |
When I run this query I get Incorrect syntax error "(". Is this the correct way of using CONVERT?
```
SELECT
DATEPART(mm,[actualclosedate]) AS [Month],
COUNT([opportunityid]) AS 'Won Opportunities',
CONVERT(SUM(ISNULL([actualvalue],1)) as numeric (10,2)) AS 'Value'
FROM [dbo].[FilteredOpportunity]
WHERE ... | If you use convert you put the type first before the expression:
```
SELECT
DATEPART(mm,[actualclosedate]) AS [Month],
COUNT([opportunityid]) AS 'Won Opportunities',
CONVERT(numeric (10,2),
SUM(
ISNULL([actualvalue],1)
)
) AS 'Value'
FROM [dbo].[FilteredOpportunity]
WHE... | Instead of CONVERT() use [CAST()](https://technet.microsoft.com/en-us/library/aa226054(v=sql.80).aspx) function.
**Syntax**
```
CAST ( expression AS data_type )
``` | Convert gives an error | [
"",
"sql",
"sql-server",
""
] |
I got an error for the following query in SQL Server 2008
> Subquery returned more than 1 value. This is not permitted when the
> subquery follows =, !=, <, <= , >, >= or when the subquery is used as
> an expression.
I want to use select command inside case statement after `THEN`
Below is the query
```
DECLARE @sta... | Try changing your `select` query like this.
```
SELECT ASSET_EVENT.PERSON_ID,
ASSET_ID,
Event_Type_id,
EVENT_START_DATE,
Event_date,
Isnull(Datediff(ss, event_start_date, Event_date), 0) AS INTERVAL,
0,
0
FROM ASSET_EVENT
INNER JOIN PERSON
ON ASS... | Edit this line
```
and ASSET_EVENT.PERSON_ID in ( CASE (LEN(@personId)) WHEN 0 THEN ASSET_EVENT.PERSON_ID ELSE (select deviceid from [dbo].[Split]( @personId , ',')) END )
```
to
```
and
(
@personId = ''
OR
EXISTS
(
select *from [dbo].[Split]( @personId , ',')
where deviceid = ASS... | select command inside then in case statement | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
i'm using Pentaho and I was wondering if it's possible to do some query like this :
```
SELECT Something
FROM Somewhere
WHERE (CASE WHEN condition1 = 0 THEN Option IN (Parameter) ELSE
(Option IN (SELECT Option FROM Somewhere_else)) END);
```
If you want some precision, i want to select everything if my conditio... | Just use regular conditions:
```
SELECT Something
FROM Somewhere
WHERE (condition1 = 0 AND Option IN (Parameter))
OR (condition1 != 0 AND Option IN (SELECT Option FROM Somewhere_else));
``` | You should try following,
```
SELECT Something
FROM Somewhere
WHERE
1 = case when condition1 = 0 THEN
case when Option IN (Parameter) then 1 else 0 end
else
case when Option IN (SELECT Option FROM Somewhere_else) then 1 else 0 end
end
``` | SELECT ALL in a CASE inside a SELECT | [
"",
"mysql",
"sql",
"select",
"pentaho",
""
] |
I have a table-valued parameter `@supplierData` in a stored procedure which has columns as follows
```
sName | sLocation | currYearExpt | currYearImpt | prevYearExpt | prevYearImpt
----------
XXX | USA | 1000 | 2000 | 1000 | 2050
YYY | U.K | 8000 | 12000 | 10000 ... | You could use the DENSE\_RANK function (<https://msdn.microsoft.com/en-us/library/ms173825.aspx>) with OVER to specify the order and a partitioning criteria. So you'll get numeric IDs for your suppliers. You could insert them into a table parameter first and than use this for your two INSERTs | Here you are. Let use `insert into select` or `select into`, they are created to do the kind of this:
```
DECLARE @supplierData TABLE
(
sName nvarchar(50),
sLocation nvarchar(50),
currYearExpt int,
currYearImpt int,
prevYearExpt int,
prevYearImpt int
);
DECLARE @SUPPLIER TABLE
(
sId int,
sName nvarcha... | Insert Table parameter to 2 different tables within a stored procedure | [
"",
"sql",
"sql-server",
"sql-server-2008",
"stored-procedures",
"cursor",
""
] |
In SAS, is there an easy way to extract records from a data set that have more than 2 occurrences.
The DUPS command gives duplicates, but how to get triplicates and higher?
For example, in this dataset:
```
col1 col2 col3 col4 col5
1 2 3 4 5
1 2 3 5 7
1 2 ... | You can achieve this using proc sql pretty easily. The below example will keep all rows from the table that are triplicates (or higher).
Create some sample data:
```
data have;
input col1 $
col2 $
col3 $
col4 $
col5 $
;
datalines;
1 2 3 4 5
1 ... | I would use `proc sql` for this, taking advantage of the `group by` and `having` clauses. Even though it's one step of code, it does require 2 passes of the data in the background, however I believe this needs to be the case whichever method you use.
```
data have;
input col1 $ col2 $ col3 $ col4 $ col5 $;
datalines;
... | How to extract triplicates or higher records in SAS | [
"",
"sql",
"sas",
""
] |
I have a table like:
```
ID TIMEVALUE
----- -------------
1 06.07.15 06:43:01,000000000
2 06.07.15 12:17:01,000000000
3 06.07.15 18:21:01,000000000
4 06.07.15 23:56:01,000000000
5 07.07.15 04:11:01,000000000
6 07.07.15 10:47:01,000000000
7 07.07.15 12:32:01,000... | **EDIT**: It is tested now: [SQL Fiddle](http://sqlfiddle.com/#!4/6a7d8/2)
The key is simply to adjust the `group by` so that anything before 6am gets grouped with the previous day. After that, the counts are pretty straight-forward.
```
SELECT TO_CHAR(CASE WHEN EXTRACT(HOUR FROM timevalue) < 6
TH... | Substract 1 day from timevalue for times lower than '06:00' at first and then:
[SQLFiddle demo](http://sqlfiddle.com/#!4/8d2a5/1)
```
select TO_CHAR(day, 'YYYY\MM\DD') day, COUNT(ID) cnt,
SUM(case when '23' < tvh or tvh <= '06' THEN 1 ELSE 0 END) as midnight,
SUM(case when '06' < tvh and tvh <= '14' THEN 1 ... | Select data grouped by time over midnight | [
"",
"sql",
"oracle",
"group-by",
""
] |
I have a need to split one record into 2 when they meet a certain criteria and I have difficulty joining them together after splitting them up.
I have this table:

For meetings that a day, I need to split them up into 2 sessions, one in the morning a... | You're not really nesting two with clauses, but you do nest one inside a union.
The `with` clause declares one or more subqueries and assigns them a name that can be used further down in the query, like a view.
So thats what you can do here as well. Move the entire `with` clause and the inline view it defines to the ... | A bit more compact solution using two subqueries (ommitning the union).
The first one for a mapping table, providing join either one to one or the split in two records.
The second subquery transform your date source adding the "Duration" key, which represents
the tree cases: AM only, PM only or both AM + PM
The rest is... | Oracle Nesting With Clauses | [
"",
"sql",
"oracle",
"common-table-expression",
""
] |
I have a data set that has timestamped entries over various sets of groups.
```
Timestamp -- Group -- Value
---------------------------
1 -- A -- 10
2 -- A -- 20
3 -- B -- 15
4 -- B -- 25
5 -- C -- 5
6 -- A -- 5
7 -- A -- 10
```
I wan... | I approach this problem by defining a group which is the different of two `row_number()`:
```
select group, sum(value)
from (select t.*,
(row_number() over (order by timestamp) -
row_number() over (partition by group order by timestamp)
) as grp
from my_table t
) t
gr... | A solution using `LAG` and windowed analytic functions:
[SQL Fiddle](http://sqlfiddle.com/#!4/bf7ab/1)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE TEST ( "Timestamp", "Group", Value ) AS
SELECT 1, 'A', 10 FROM DUAL
UNION ALL SELECT 2, 'A', 20 FROM DUAL
UNION ALL SELECT 3, 'B', 15 FROM DUAL
UNION ALL S... | SQL Grouping by Ranges | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I tried to fetch data from a oracle sql table with the count of records. I tried like following,
```
SELECT *,
(COUNT(BRAND_ID) AS TOTAL)
FROM
(
SELECT BRAND_ID,
BRAND_CODE,
BRAND_TITLE
FROM BRAND
WHERE ACTIVE = '1'
ORDER BY BRAND_TITLE ASC
OFF... | I guess You should remove `*` from `select statement` in the first line. Try the below one.
```
SELECT (COUNT(BRAND_ID) AS TOTAL)
FROM
(
SELECT BRAND_ID,
BRAND_CODE,
BRAND_TITLE
FROM BRAND
WHERE ACTIVE = '1'
ORDER BY BRAND_TITLE ASC
OFFSET 10 ROWS
... | I don't have 12c, so can't test, but maybe this is what you're after?
```
SELECT *
FROM
(
SELECT BRAND_ID,
BRAND_CODE,
BRAND_TITLE
FROM (select b.*,
count(brand_id) over () total
from BRAND b
WHERE ACTIVE = '1'
ORDER BY BRAN... | ERROR: ORA-00923: FROM keyword not found where expected | [
"",
"sql",
"oracle",
""
] |
I have two tables which I join so that I may compare a field and extract records from one table where the field being compared is not in both tables:
```
Table A
---------
Comp Val
111 327
112 234
113 265
114 865
Table B
-----------
Comp2 Val2
111 7676
112 5678
```
So what im doing is to joi... | I think you want this, though:
```
select *
from TableA a
where
not exists (select b.Comp2 from TableB b where a.Comp1 = b.Comp2)
```
That will find all records in A that don't exist in B. | Just prefix the `*` with the desired table name, like this:
```
select TableA.* into Result from TableA
inner join TableB
on (TableB.Comp2 = TableA.Comp)
where TableB.Comp2 <> TableA.Comp
``` | Inner Join Tables But Select From One Table Only | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have been stuck in a recent problem with a SQL Query. What I'm trying to archieve is to get each product in the store and show how many of them has been sold each month. However, sometimes there are some months where these products were not sold, which means they won't be displayed.
For instance, this is the result ... | This works for me:
```
SELECT k.artikelnr, c.datefield AS `Month`, COALESCE(s.Quantity, 0) AS Sold
FROM (
SELECT artikelnr
FROM store_shop_korb
GROUP BY artikelnr
) k
JOIN office_calendar c
LEFT JOIN (
SELECT artikelnr, MONTH(date_insert) AS monthfield, SUM(menge) AS Quantity
FROM store_shop_korb
... | I have tried this in MSAccess and it seems to work OK
```
SELECT PRODUCT, CALENDAR.MONTH, A
FROM CALENDAR LEFT JOIN (
SELECT PRODUCT, MONTH(SALEDTE) AS M, SUM(SALEAMOUNT) AS A
FROM SALES
WHERE SALEDTE BETWEEN #1/1/2015# AND #12/31/2015#
GROUP BY PRODUCT, MONTH(SALEDTE) ) AS X
ON X.M = CALENDAR.MONT... | Get product total sales per moth, with 0 in the gaps | [
"",
"mysql",
"sql",
""
] |
I’m trying to make a query that returns the difference of days to get the average of days in a period of time. This is the situation I need to get the max date from the status 2 and the max date from the status 3 from a request and get how much time the user spend on that period of time
So far this is the query I Have... | You'll need to use subqueries since the groups for the min and max times are different. One query will pull the min value where the status is 2. Another will pull the max value where the status is 3.
Something like this:
```
SELECT MinDt.[User], minDt.MinTime, MaxDt.MaxTime, datediff(d,minDt.MinTime, MaxDt.MaxTime) a... | What is the SQL-Server version? Maybe you could use your query as CTE and do a follow-up SELECT where you can use the Min and Max date as date period.
EDIT: Exampel
```
WITH myCTE AS
(
put your query here
)
SELECT * FROM myCTE
```
You can use myCTE for further joins too, pick out the needed date, use sub-select, wha... | SQL Query AVG Date Time In same Table Column | [
"",
"sql",
"sql-server",
"max",
"average",
"datediff",
""
] |
I would like to query by the following
```
(statement1 AND statement2 AND (statement3 OR statement4 ))
```
this is my hive query, I verified that it doesn't work since it only returns statement3, and I know there are case where statement4 is true
```
SELECT
cid,
SUM(count) AS total_count
FROM
count_by_day
WHE... | 1. Is count a real variable name? Double check that.
2. Also check to make sure your time is a numeric type, probably a bigint. If it isn't cast it as a big int like this:
```
WHERE cast(time as bigint) >= 1435536000 AND cast(time as bigint) < 1436140800
```
3. Try changing your or statement to an in statemen... | Always learnt to use UNION instead of OR in relational databases. Try and see if union solves your issue.
```
select cols
from table
where statement1 AND statement2 AND statement3
union all
select cols
from table
where statement1 AND statement2 AND statement4
``` | How do you group OR clause in WHERE statement using HIVE | [
"",
"sql",
"hadoop",
"hive",
"bigdata",
""
] |
I have a query that returns a large (10000+ rows) dataset. I want to order by date desc, and display the first 40 results. Is there a way to run a query like this that only retrieves those 40 results without retrieving all 10000 first?
I have something like this:
```
select rownum, date, * from table
order by date de... | ```
SELECT *
FROM (SELECT *
FROM table
ORDER BY date DESC)
WHERE rownum <= 40
```
will return the first 40 rows ordered by `date`. If there is an index on `date` that can be used to find these rows, and assuming statistics are up to date, Oracle should choose to use that index to identify the 40 ... | Oracle 12c has introduced a [row limiting](https://oracle-base.com/articles/12c/row-limiting-clause-for-top-n-queries-12cr1) clause:
```
SELECT *
FROM table
ORDER BY "date" DESC
FETCH FIRST 40 ROWS ONLY;
```
In earlier versions you can do:
```
SELECT *
FROM ( SELECT *
FROM table
ORDER BY "dat... | Pagination of large dataset | [
"",
"sql",
"oracle",
"pagination",
""
] |
Oracle DB.
Spring JPA using Hibernate.
I am having difficulty inserting a Clob value into a native sql query.
The code calling the query is as follows:
```
@SuppressWarnings("unchecked")
public List<Object[]> findQueryColumnsByNativeQuery(String queryString, Map<String, Object> namedParameters)
{
List<Object[]> ... | THE ANSWER: Thank you both for your answers. I should have updated this when i solved the issue some time ago. In the end I used JDBC and the problem disappeared in a puff of smoke! | I'm afraid your assumptions about CLOBs in Oracle are wrong. In Oracle CLOB locator is something like a file handle. And such handle can be created by the database only. So you can not simply pass CLOB as bind variable. CLOB must be somehow related to database storage, because this it can occupy up to 176TB and somethi... | Setting a Clob value in a native query | [
"",
"sql",
"oracle",
"jpa",
"clob",
"nativequery",
""
] |
I have created a query which returns a list of products with their fields and values. Now I want to search through fields for a certain value and get a resultlist matching this search query. The problem is that I want an AND construction, so fieldx value must be like %car% and fieldy value must be like %chrome%.
Here`... | A relatively simple way to do this is to use `group by` and `having`:
```
SELECT p.id as product
FROM product p JOIN
field pf
ON pf.product_id = p.product_id JOIN
field_val pfv
ON pfv.field_id = pf.field_id
WHERE (field_name = 'meta_title' AND field_value LIKE '%Example%') OR
(field_name = '... | First: I would go for the easiest way. If Prerak Solas solution works and the performance is OK for you, go for it.
An other solution is to use a pivot table. With this the select of your table would return something like this:
```
product | meta_title | meta_kw | prod_name
pr1 | Example text | keyword... | Mysql filter (AND) query on multiple fields in multiple joined rows | [
"",
"mysql",
"sql",
"join",
"having",
""
] |
I need to find max date from a table(mysql database). I am storing my date as varchar.
`select max(completion_date) from table_name` returns wrong value.
<http://sqlfiddle.com/#!9/c88f6/3> | Assuming the date time format you have in your fiddle (e.g. '12/19/2012 05:30 PM') then:
```
select max(STR_TO_DATE(completion_date, '%m/%d/%Y %l:%i %p')) from test;
```
<http://sqlfiddle.com/#!9/c88f6/15>
It's unclear if you want to factor the time into your rankings or just the date. This example accounts for time... | I am not sure why you would want to keep it as varchar not date.
But this will work for varchar:
```
SELECT completion_date
FROM test
ORDER BY STR_TO_DATE(completion_date, '%m/%d/%Y') DESC LIMIT 1;
```
<http://sqlfiddle.com/#!9/c88f6/10> | max value from varchar date | [
"",
"mysql",
"sql",
"date",
""
] |
I want to count user\_id from `courses_taken` and `quiz_attempts` table but my query brings me wrong numbers.
```
SELECT
u.id,
u.email,
u.user,
u.joined,
MAX(qa.last_attempt_time) as last_attempt_time,
COUNT(qa.user_id) total_quiz,
COUNT(ct.user_id) total_courses
FROM users u
LEFT JOIN... | What you can do is use `COUNT DISTINCT` on a column which varies uniquely with the value that you are trying to count, i.e.:
```
...
COUNT(DISTINCT qa.id) total_quiz,
COUNT(DISTINCT ct.course_id) total_courses
...
```
[SqlFiddle here](http://sqlfiddle.com/#!9/66834/1) | You probably have a cartesian product problem because of the join. The better solution is to pre-aggregate the results. However, in many cases if the tables are not too big, then `count(distinct)` solves the problem:
```
SELECT u.id, u.email, u.user, u.joined,
MAX(qa.last_attempt_time) as last_attempt_time,
... | Count different totals from multiple tables in mysql grouped by user_id in one query | [
"",
"mysql",
"sql",
""
] |
I've been looking for an answer to this but couldn't find anything the same as this particular situation.
So I have a one table that I want to remove duplicates from.
```
__________________
| JobNumber-String |
| JobOp - Number |
------------------
```
So there are multiples of these two values, toge... | Original Table Values:
```
JobNumber Jobop
123 100
123 101
456 200
456 201
780 300
```
Code Ran:
```
DELETE FROM table
WHERE CONCAT(JobNumber,JobOp) NOT IN
(
SELECT CONCAT(JobNumber,MIN(JobOp))
FROM table
GROUP BY JobNumber
)
```
Ending Table Value... | With SQL Server 2008 or higher you can enhance the MIN function with an OVER clause specifying a PARTITION BY section.
Please have a look at <https://msdn.microsoft.com/en-us/library/ms189461.aspx> | SQL Remove Duplicates, save lowest of certain column | [
"",
"sql",
"sql-server",
"database",
""
] |
My users should be able to search the database by entering a search term in an input box and selecting the column they'd like to search on from a dropdown box.
However, I can't find a way to parameterize a query in golang such that the column name is recognized as a column name instead of a value. Let me give an examp... | This is trying to help keep you safe from bad args (prevent things like SQL injection) but isn't designed to do replacement on anything other than a value. You want it to insert a table name. Unfortunately for you the code is aware of `col`'s type (string) and quotes it because in SQL it's nvarchar and that's how they ... | You should take a look at this package.
<https://github.com/gocraft/dbr>
It's great for what you want to do.
```
import "github.com/gocraft/dbr"
// Simple data model
type Suggestion struct {
Id int64
Title string
CreatedAt dbr.NullTime
}
var connection *dbr.Connection
func main() {
db, ... | How can I use a parameterized query to search on a column by its name? | [
"",
"mysql",
"sql",
"go",
"sql-injection",
""
] |
I have this piece of code from which i wish to get a single array that contains all value.
```
$sql = "SELECT * FROM interest where interest='".$interest."' and userid!='".$myuserid."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
... | Take one array variable before while loop started like `$user_data = array();` and in inner loop you have to set `$user_data[] = $row2;`
```
if (mysqli_num_rows($result) > 0) {
$user_data = array();
while($row = mysqli_fetch_assoc($result)) {
$userid = $row["userid"];
if($searchtype == ... | Create an array variable like `$a=array();` at the start of your code
Get row value in array $a[]=your row value(while loop), then print this outside loop you will get all value in single array print like
```
print_r($a);
``` | Merge multiple array to single array | [
"",
"mysql",
"sql",
"arrays",
"multidimensional-array",
""
] |
I tried to create trigger `AFTER UPDATE` via phpmyadmin with body INSERT:
```
BEGIN
INSERT INTO updatespersonal SET (user, time, type, operator) VALUES (NEW.idDetailToUsers, CURRENT_TIMESTAMP(), "detailtousers", "update");
END
```
But I get error, reason that I can not understand:
> # 1064 on line 2
May be problem ... | Error in **Insert** Statement, remove **SET** keyword:
```
INSERT INTO updatespersonal (user, time, type, operator) VALUES (NEW.idDetailToUsers, CURRENT_TIMESTAMP(), "detailtousers", "update");
``` | Your syntax is incorrect. You no need `SET` when using **[INSERT INTO](http://www.w3schools.com/php/php_mysql_insert.asp)**.
Your code should be:
```
BEGIN
INSERT INTO updatespersonal (user, time, type, operator) VALUES (NEW.idDetailToUsers, CURRENT_TIMESTAMP(), "detailtousers", "update");
END
``` | Trigger error INSERT Mysql | [
"",
"mysql",
"sql",
""
] |
I am having getting proper outputs for this functions. Does datediff only calculate the difference in days for days in the same month?
When I pass in a date in the form of '01 Jan 2015' it always sends me back a 0 =/ did I miss something in my logic or syntax?
```
CREATE FUNCTION dbo.CanPolicy
(
@ReservationID int... | No, DATEDIFF counts dates in between. Try:
```
SELECT DATEDIFF(day,{ts'2105-01-01 00:00:00'},{ts'2105-04-01 00:00:00'})
```
Could be a date format issue...
Are you sure, that @ResDate is set correctly?
EDIT: New approach with CTE
```
DECLARE @ReservationID INT=123;
DECLARE @CancelationDate DATE=GETDATE();
WITH Re... | I think the correct and short version of your function is this - please give it a try:
```
CREATE FUNCTION dbo.CanPolicy
(
@ReservationID int,
@CancellationDate date
)
RETURNS smallmoney
AS
BEGIN
DECLARE @DepositPaid smallmoney,
@CanceledDaysAhead int
SELECT @DepositPaid =... | Trouble with TSQL calculation - date diff giving me troubles | [
"",
"sql",
"sql-server",
"t-sql",
"datediff",
"udf",
""
] |
I have a user table that consists of these columns:
```
| id | username | password | email | pants_size_id | shirt_size_id |
```
`pants_size_id` and `shirt_size_id` are filled with foreign tables id keys where I store a list of sizes for pants and shirts in different country specific measures, example of `pants_size`... | Cato has the right answer, I can't exactly respond to it because of my rep but the logic in your other answer doesn't make sense from a relational standpoint.
Users don't belong to a size, instead, Users have a size.
To me it sounds like you mixed up the foreign and local key assignment it should be User->hasOne(pant... | this is how I made it work:
in USER model:
```
public function pants_size(){
return $this->belongsTo('App\Pants_size');
}
public function shirt_size(){
return $this->belongsTo('App\Shirt_size');
}
```
In Pants\_size and Shirt\_size Models:
```
public function use... | confusion over which relationship to use in models for these two tables | [
"",
"sql",
"laravel",
"eloquent",
"relationship",
""
] |
I have several tables that have a common field (column) called `LastName` in a `MySQL database`. Several of the rows in these tables are in mixed case so they don't get selected properly when doing a `SELECT`.
How can I convert those columns to all UPPER CASE? I can easily handle any new entries to convert them to upp... | this would work:
```
UPDATE table_name SET `column_name` = UPPER( `column_name` )
``` | would do the job
```
update table set LastName=UPPER(LastName);
```
NOTE - if you are running from MySQL workbench you may have to disable safety mode or add a where clause (eg WHERE id>0) otherwise it wont run. | Update a field in SQL | [
"",
"mysql",
"sql",
""
] |
Last time when I was working with my SQL Server 2014 and suddenly due to a power failure my database goes corrupted and next time after running DBCC CHECKDB I found some of stored procedures that I have created on my SQL Server are still missing. So there is any method from which I can create a successful backup for my... | One Possibilty is:
In SQL Server Manangement Studio **rightlick on your Database - Tasks - Generate Scripts...**
Here you can specify which object you want to script and where to save the script file.
What's my favourite solution (though it's more work) is to have all my databases in **Database Projects** in Visual St... | The correct solution here is to backup the entire database, as you stored procedure will have dependencies - like tables, columns, views, etc. that are in the database.
If you just want to retrieve the text of the stored procedure and save it to a file, you can use `sp_helptext`. For example:
```
sp_helptext sp_proced... | How can I back up a stored procedure in SQL Server? | [
"",
"sql",
"sql-server",
"sql-server-2014",
""
] |
I've always been under the assumption that not exists is the way to go instead of using a not in condition. However, I doing a comparison on a query I've been using, I noticed that the execution for the Not In condition actually appears to be faster. Any insight into why this could be the case, or if I've just made a h... | try
```
SELECT DISTINCT a.SFAccountID, a.SLXID, a.Name
FROM [dbo].[Salesforce_Accounts] a WITH(NOLOCK)
JOIN _SLX_AccountChannel b WITH(NOLOCK)
ON a.SLXID = b.ACCOUNTID
AND b.STATUS IN ('Active','Customer', 'Current')
JOIN [dbo].[Salesforce_Contacts] c WITH(NOLOCK)
ON a.SFAccountID = c.SFAccountID
... | I think the missing index cause the difference for `EXISTS()` and `IN` operations.
Although the question do not ask for a better query, but for me I'll try to avoid the Distinct like this
```
SELECT
a.SFAccountID, a.SLXID, a.Name
FROM
[dbo].[Salesforce_Accounts] a WITH(NOLOCK)
CROSS APPLY
(
... | Not Exists vs Not In: efficiency | [
"",
"sql",
"sql-server",
"t-sql",
"exists",
"sql-execution-plan",
""
] |
I have tried with the following sample
```
SELECT
FORMAT(CONVERT(DATETIME,'01011900'), 'dd/MM/yyyy')
FROM
identities
WHERE
id_type = 'VID'
``` | Try this:
```
SELECT FORMAT(CONVERT(DATETIME,STUFF(STUFF('01011900',5,0,'/'),3,0,'/')),'dd/MM/yyyy')
```
Insert `/` using **`STUFF`**, and then convert it.
```
STUFF(STUFF('01011900',5,0,'/'),3,0,'/') -- 01/01/1900
```
**Update**:
I tried the following also,
```
DECLARE @DateString varchar(10) = '12202012' --19991... | Your data should be 19000101.So your input needs to be modified first then we need to use Convert to get your appropriate format.
```
declare @inp varchar(10) = '01011900'
select CONVERT(varchar, cast(right(@inp,4)+''+left(@inp,4) as datetime), 101)
--Output : 01/01/1900
``` | Convert the string '01011900' or '19990101' or any format to date and with required format '01/01/1990' | [
"",
"sql",
"sql-server",
""
] |
I'm using an sqlite database for my Java application and I have a single varchar column with a bunch user stats that is written, read, and parsed by my Java program. What I want to do is have an query that can sort the rows by the last stat in the column. The stats are separated by commas and their lengths vary so I ne... | As a quick and hacky solution (low performance if you have huge amount of data):
```
SELECT * FROM [tbl] ORDER BY CAST(SUBSTR([col], INSTR([col], '],') + 2) AS INTEGER);
```
But as Hayley suggested, to re-evaluate the data, you can use:
```
INSERT INTO [new-tbl]
SELECT SUBSTR(val, 0, c1),
SUBSTR(val, c1+1, c2... | The solution to you problem is not the answer to your question. A delimited list of stats should not be a column in your table. See [this question](https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad) for more information. Instead, re-evaluate your schema and sor... | SQLite Order Rows by Last Characters in a String | [
"",
"sql",
"database",
"sqlite",
""
] |
I'm trying to delete an item `items` table. And also from `saves` table if it exists.
This is the 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 'i LEFT JOIN saves s ON i.id = s.item_id`
```
DELETE FROM items i
LEFT JOIN s... | **If you want to delete from a single table, say `items` try this::**
```
DELETE i FROM items i
LEFT JOIN saves s
ON i.id = s.item_id
WHERE i.id = ? AND s.item_id = ?
AND
NOT EXISTS (SELECT id FROM pending_wins WHERE item_id = ?)
AND
NOT EXISTS (SELECT id FROM bids WHERE item_id = ?)
```
**If you want to delete recor... | ```
DELETE i, s
FROM items i
LEFT JOIN saves s
ON i.id = s.item_id
WHERE s.item_id = ?
AND
NOT EXISTS (SELECT id FROM pending_wins WHERE item_id = ?)
AND
NOT EXISTS (SELECT id FROM bids WHERE item_id = ?)
``` | MySQL - Delete item from two tables | [
"",
"mysql",
"sql",
""
] |
I'm pretty new to SQL, trying to wrap my head around it, but it's getting a little confusing. Here's a simplified version of what I'm working with.
I have this table called `people`:
```
+----+------------+-----------+
| id | name | parent_id |
+----+------------+-----------+
| 1 | Bob | 3 |
| ... | This can be solved using a simple `JOIN`.
To select the list of children:
```
SELECT c.name
FROM people p
JOIN people c ON c.parent_id = p.id
WHERE p.parent_id = 0
```
To select the list of grandchildren:
```
SELECT gc.name
FROM people p
JOIN people c ON c.parent_id = p.id
JOIN people gc ON gc.parent_id = c.id
WHER... | First of all, it's very important to know that this question is very easy to answer, IF you know that you're working with a fixed set of generations (down to grandchildren, for example). If this table is ultimately going to have many generations, and you want to (for example) find all of Kyle's descendants through the ... | SQL query to select only grandchildren | [
"",
"mysql",
"sql",
""
] |
I ran a simple query:
```
UPDATE table
SET user_id = '123456'
WHERE user_id = '234567'
```
Then I got the error message:
```
(2942 row(s) affected)
Msg 2627, Level 14, State 1, Line 3
Violation of PRIMARY KEY constraint 'PK__users__6B24EA82'. Cannot insert duplicate key in object 'dbo.users'. The duplicate key val... | No, this means you would have made changes to 2942 rows, except one or more of them violates the PRIMARY KEY constraint so they were rolled back. | Assuming that `user_id` is a primary key (which the error message suggests based on the value in the error message), then the query:
```
UPDATE table
SET user_id = '123456'
WHERE user_id = '234567';
```
could never affect more than one row in `table`. `user_id` is a primary key, so it is unique. The `where` c... | What exactly does "(X row(s) affected)" mean? | [
"",
"sql",
"sql-server-2012",
""
] |
I have two tables which looks like :
**First table**
```
CustomerId CustomerName
110 XYZ
111 ABC
112 PQR
113 LMN
```
Second Table
```
CustomerId PhoneNumber
110 9823983298329
111 ... | This is a form of pivot; you just need a column to pivot on. You can get this result using conditional aggregation and `row_number()`:
```
select t1.CustomerId, t1.CustomerName,
max(case when seqnum = 1 then PhoneNmber end) as PhoneNmber1,
max(case when seqnum = 2 then PhoneNmber end) as PhoneNmber2
from... | Use a `GROUP BY` to find each customer's min and max phone no. Do a `LEFT JOIN` with that result:
```
select f.CustomerId,
f.CustomerName,
s.min_ph,
case when s.min_ph <> s.max_ph then s.max_ph else null end
from firsttable f
left join (select CustomerId,
min(PhoneNumber) min... | How to get values from rows on one table to column of other | [
"",
"sql",
"database",
"oracle",
""
] |
How do I get N records before given one?
I have the following table structure:
```
Id, Message
1, John Doe
2, Jane Smith
3, Error
4, Jane Smith
5, Michael Pirs
7, Gabriel Angelos
8, Error
```
Is there a way to get the N records before each Error and join all such records?
So the expected result for the N =2 will be
... | You need to create a row number column if your Ids do not increment without gaps. Then you can use a simple join to find the previous N. Your previous N could overlap... so you have to add `distinct` if you do not want duplicates.
```
declare @N as integer
set @N=2
;with cte_tbl (Id, Message, rownum) AS
(
select *, R... | You can do this using `cross apply`. The logic is a bit different from typical applications, because you only want the records from the `cross apply` subquery:
```
select t2.*
from table t cross apply
(select top 2 t.*
from table t2
where t2.id < t.id
order by t2.id desc
) t2
where t2.messa... | How do I get N records before given one? | [
"",
"sql",
"sql-server",
""
] |
Below is my sql query:
```
IIf(remedy_src.Position Is Null,(mid(remedy_src.User,instr(1,remedy_src.User,"(")+1,instr(1,remedy_src.User,")")-2-instr(1,remedy_src.User,"(")+1)),remedy_src.Position) AS [Adjusted User]
```
The point is to extract string from a field. Here's an example of the value:
```
n123456 (name las... | Here's how I got a solution for this issue, kind of completely reqwriting the code to exclude any finction to return errors.
```
IIf(remedy_src.Position Is Null,replace(replace(right(remedy_src.User,len(remedy_src.User)-instr(1,remedy_src.User,' ')),'(',''),')',''),remedy_src.Position) AS [Adjusted User]
``` | You could try to catch the error:
```
IIF(IsERROR(IIf(remedy_src.Position Is Null,(mid(remedy_src.User,instr(1,remedy_src.User,"(")+1,instr(1,remedy_src.User,")")-2-instr(1,remedy_src.User,"(")+1)),remedy_src.Position)),
remedy_src.user,
IIf(remedy_src.Position Is Null,(mid(remedy_src.User,instr(1,remedy_src.User,"(")... | #Func! Error on iif query in MS Access | [
"",
"sql",
"ms-access",
""
] |
I run the following SQL query on my Microsoft SQL Server (2012 Express) database, and it works fine, executing in less than a second:
```
SELECT
StringValue, COUNT(StringValue)
FROM Attributes
WHERE
Name = 'Windows OS Version'
AND StringValue IS NOT NULL
AND ProductAssociation IN (
SELECT ID
FROM Produ... | Try this:
```
SELECT
a.StringValue, COUNT(a.StringValue)
FROM Attributes a
INNER JOIN ProductAssociations p ON a.ProductAssociation = p.ID
AND p.ProductCode = 'MyProductCode'
LEFT JOIN Attributes a2 ON a2.ProductAssociation = p.ID
AND a2.Name = 'Is Test' AND a2.BooleanValue = 0
WHERE
Name = 'Windows... | > Why? What am I doing wrong?
You are trying to *compile* a query that needs to satisfy multiple distinct conditions, based on the variable. The optimizer must come up with *one* plan that works in *both* cases.
Try to avoid this like the plague. Just issue two queries, one for one condition one for the other, so tha... | Simple change causes SQL query execution time to dramatically increase | [
"",
"sql",
"sql-server",
"t-sql",
"execution-time",
"sql-execution-plan",
""
] |
I am trying to execute a SQL query in my rails app. The following executes normally since it is looking for an exact match:
```
connection.query("SELECT *
FROM test
WHERE y=#{connection.quote(name)}
ORDER BY x ASC")
```
I want to use the LIKE operator to find par... | You need to add the `%`s in Ruby before quoting:
```
connection.query("SELECT *
FROM test
WHERE y LIKE #{connection.quote('%' + name + '%')}
ORDER BY x ASC")
```
`connection.quote` will add single quotes to produce a valid SQL string literal and you want to get t... | Since you use Rails anyway I suggest using [ActiveRecord's query interface](http://guides.rubyonrails.org/active_record_querying.html) instead of plain SQL.
With `ActiveRecord` the query could be written like this:
```
Test.where("y LIKE ?", "%#{name}%").order(:x)
```
You need to have an `ActiveRecord` model named `... | SQL query in Rails using % and LIKE | [
"",
"sql",
"ruby-on-rails",
"ruby",
""
] |
Apologies if the title is not completely accurate, but I am not sure how to phrase my question exactly. I would like to return only rows where the results include all items in the IN statement grouped on particular columns. So my query is:
```
SELECT [DRSY],
[DRRT],
[DRKY],
[DRDL01... | I believe this can be done by GROUPING and then ensuring the DISTINCT count is equal to the number of search items:
```
SELECT [DRSY],
[DRRT]
FROM dbo.f0005
WHERE DRKY IN ('FC', 'OO', 'SH')
GROUP BY [DRSY], [DRRT]
HAVING COUNT(DISTINCT DRKY) = 3;
```
**Edit, Re Ensuring Count of Items remains... | What about
```
SELECT DRSY, DRRT, DRKY, DRDL01 FROM dbo.f0005 a
WHERE exists (
SELECT * FROM dbo.f005 b WHERE DRKY = "FC" and a.DRSY = b.DRSY and a.DRRT = b.DRRT
)
AND exists (
SELECT * FROM dbo.f005 c WHERE DRKY = "00" and a.DRSY = c.DRSY and a.DRRT = c.DRRT
)
AND exists (
SELECT * FROM dbo.f005 d WHERE DRKY... | Return records in SQL that include all values from IN clause | [
"",
"sql",
"sql-server",
"t-sql",
"exists",
""
] |
I have this table X with only one column, A. How can I generate a random number in each row, within specific values? Let's say I want random numbers to be either 1, 2 or 999 (3 numbers), I would have a column B looking something like this:
```
A | B
-----
12| 1
33| 999
67| 1
20| 2
...
```
I've tried the `dbms_random`... | Here is one method using `case`:
```
select x.a,
(case when rand < 2 then 1 when rand < 3 then 2 else 999 end) as b
from (select x.*,
dbms_random.value(1, 4) as rand
from x
) x;
``` | You could store the values you want (1, 2, 999, bla, bla, bla) in a table, and join into it in a random order, like:
```
create table x (a int);
insert into x values (12);
insert into x values (33);
insert into x values (67);
insert into x values (20);
create table y (z int);
insert into y values (1);
insert into y... | SQL Generate Random Number | [
"",
"sql",
"database",
"oracle",
"random",
""
] |
This is my table structure:
```
CUST_ID ORDER_MONTH
---------------------
1 1
1 5
2 3
2 4
```
My objective is to tag these customers as either New or Returning customers.
When I filter the query lets say for month 1 then customer 1 should have the tag 'New' but when I filter it for month... | If you insist on using a case statement, the logic would be something like "If this is the first month for that user, write new, otherwise write returning." The query would be as follows:
```
SELECT CASE
WHEN m.month = (SELECT MIN(month) FROM myTable WHERE customer = m.customer) THEN 'New'
ELSE 'Returning' END... | You don't need a JOIN and a case statement would probably be overkill...
```
SELECT CUST_ID, IF(COUNT(1)>1, 'Returning', 'New') AS blah
FROM the_table
WHERE ORDER_MONTH <= the_month
GROUP BY CUST_ID
;
```
Of course, using just month is going to cause problems after a year (or really, after passing December.)
This wo... | CASE Statement instead of inner join | [
"",
"mysql",
"sql",
"logic",
""
] |
I am making attempts to run my first dynamic pivot in SQL Server 2012.
My `#temp` table that I am using for the dynamic pivoting looks like this.
```
YearMonth Agreement nr Discount
------------------------------------
201303 123 1
201303 12 0
201304 1 ... | The cause of the error is that you're missing a parenthesis before you alias the Pivot. More than this however your pivot was rather inefficient.
You should select what you need for the source table in your pivot otherwise it could run for a long time and produce a lot of rows with null returns.
The below is fixed an... | You are missing a parenthesis
```
SET @DynamicPivotQuery =
N'SELECT [Agreement nr],YearMonth , ' + @ColumnName + '
FROM #FINAL
PIVOT(
COUNT([agreement nr])
FOR YearMonth IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
``` | Dynamic pivoting SQL Server 2012 | [
"",
"sql",
"sql-server-2012",
"dynamic-pivot",
""
] |
I have 2 fields.
Birth= Datatype Decimal(12,4) & Date = Datatype Date
```
Birth Date
19650101 2015-07-09
```
how do i get a result that looks like this
i want the result to be like this
```
Birth Date
1965-01-01 2015-07-09
```
where the Birth is a Date datatype and not a dec... | To convert the number `19650101` to a date use
```
CONVERT(DATETIME, CAST(Birth AS VARCHAR(8)), 112)
```
To get the number of years (to one decimal) you could do:
```
ROUND(
DATEDIFF(day,
CONVERT(DATETIME, CAST(Birth AS VARCHAR(8)), 112),
[Date])/365.25
,1)
```
Which won't be exact but sh... | You can use this:
```
-- Create demo data
CREATE TABLE #dates(birth int, date date)
INSERT INTO #dates(birth,date)
VALUES(19650101,N'2015-07-09')
-- Your work
SELECT CONVERT(date,CONVERT(nvarchar(max),birth),112) as birth, date,
DATEDIFF(year,
CONVERT(date,CONVERT(nvarchar(max),birth),112),
... | Convert Decimal or Varchar into Date | [
"",
"sql",
"sql-server",
"date",
"casting",
"converters",
""
] |
I'm writing a query that generates statistics based on postcodes and I need to be able to count the number of matching records that are within a range of postcodes except when they exist in a secondary table. This is part of a larger query and I need the count of records for each postcodes in columnar format rather tha... | You could use a left join instead.
```
SELECT
SUM
(
CASE WHEN PostCode BETWEEN 2000 AND 2099
AND pcti.PostCode is null
THEN 1
ELSE 0
END
)
FROM #People p
left join #PostcodesToIgnore pcti on pcti.PostCode = p.PostCode
``` | You could remove the `SUM` and push the query into a derived table or CTE.
The following works
```
SELECT SUM(PostCodeFlag)
FROM (SELECT CASE
WHEN PostCode BETWEEN 2000 AND 2099
AND PostCode NOT IN (SELECT PostCode
FROM #PostcodesTo... | Excluding records within an aggregate function based on presence of value in another table | [
"",
"sql",
"sql-server",
""
] |
I can easily select all my columns from a table with:
```
SELECT * FROM foo
```
But if I want to rename the column `bar` in `foobar`, I need to specify all the fields manually. This make my query not robust if a new column is added to the table:
```
SELECT a,b,c,d,bar AS foobar FROM foo
```
Is there a possibility t... | Yes you can do the following:
```
SELECT bar AS foobar, a.* from foo as a;
```
But in this case you will get bar twice: one with name `foobar` and other with bar as `*` fetched it.. | There's not really a great way to get at what you're after. Typically, best practices dictate that you should avoid `SELECT * ...` for performance reasons. Especially for the reason you just specified - say you add a large field to this table that is irrelevant to the query at hand. You're still retrieving the data wit... | How to SELECT * and rename a column? | [
"",
"mysql",
"sql",
""
] |
I'm trying to do something like:
```
$results = $query->leftJoin('checklist_items', function($join) use ($days) {
$join->on('users.id', '=', 'checklist_items.user_id')
->on('checklist_items.due_date', 'IN', $days);
})
->where('checklist_items.user_id', null)
->limit(10)
->get();
```
This is an... | I think you would need to use `DB::raw()` so it doesn't try to quote your days and wrap your days in parenthesis as well. This should do the trick.
```
$days = '(\'2015-07-09\', \'2015-07-10\')';
$results = DB::table('users')->leftJoin('checklist_items', function($join) use ($days) {
$join->on('users.id', '=', 'ch... | You can use `->whereIn()` within the `->leftJoin()` closure (Tested in Laravel 5.7.16):
```
$days = ['2015-07-09', '2015-07-10'];
$results = \DB::table('users')
->leftJoin('checklist_items', function($join) use ($days) {
$join->on('users.id', '=', 'checklist_items.user_id')
->whereIn('checklist... | Laravel 5: Join On with IN query | [
"",
"sql",
"laravel",
""
] |
I need a table A with 4 columns for order numbers: Order1, Order2, Order3, Order4 (I know, it's horrible, but that's a given).
And I have to find the records in table B, where the match is that any value in any order column in table A could be in any order in column B:
```
A.Order1 = B.Order1 OR
A.Order1 = B.Order2 O... | The only way to do this with the model design you have is something (as @GordonLinoff suggested) like this:
```
where b.order1 in (a.order1, a.order2, a.order3, a.order4) or
b.order2 in (a.order1, a.order2, a.order3, a.order4) or
b.order3 in (a.order1, a.order2, a.order3, a.order4) or
b.order4 in (a.... | You can unpivot the columns in one table using a cross apply and then check if the value from the cross apply is in any of the columns from the other table.
It does not *automatically* work if you add new columns but you will only have to add them in one or two places.
[SQL Fiddle](http://sqlfiddle.com/#!6/44663/1)
... | SQL WHERE matching any value in any column | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I have a few related tables containing film, actor, and category data. I am trying to sum the length of the films in a particular category for each actor.
Here's what I have to try and include the sum of a category ID subquery in my results:
```
SELECT actor.actor_id, (SELECT SUM(length) from film WHERE category_id=1... | Here's how I got to what I needed:
```
SELECT actor.actor_id, SUM(film.length) as total
FROM actor
JOIN film_actor USING(actor_id)
LEFT JOIN film on film_actor.film_id = film.film_id AND film.film_id IN (SELECT film_id FROM film_category WHERE film_category.category_id = 14)
GROUP BY actor.actor_id
``` | You need an outer join and the criteria on category belongs in the on clause of the outer join:
```
select a.actor_id,
sum(f.length) as total
from actor a
join film_actor fa
on a.actor_id = fa.actor_id
join film f
on fa.film_id = f.film_id
left join film_category fc
on fc.film_id = f.film_id... | SQL: Select the sum of a subquery | [
"",
"mysql",
"sql",
"sum",
"subquery",
"aggregate-functions",
""
] |
I have a table of people, and I want to pull the most recent record of event, but there may not be one.
So my problem is that even though I'm left joining to make sure I'm getting a record for each person, I'm only bringing back people that have events because I'm pulling the Max of a date as a criteria.
```
SELECT *... | One way to do this is to use a correlated subquery in the join that checks that there doesn't exists any event for the same person with a later date:
```
SELECT *
FROM tbl_people p
LEFT JOIN tbl_events e
ON p.People_UID = e.People_UID
AND NOT EXISTS (
SELECT 1 FROM tbl_Events
WHERE e.People_UI... | ```
select * from
( SELECT *, row_number() over (partition by tbl_people.name order by tbl_events.Event_Date desc) as rn
FROM tbl_people
LEFT JOIN tbl_events
ON tbl_people.People_UID = tbl_events.People_UID
WHERE tbl_people.Active = 1 ) t
where t.rn = 1
``` | Left Join most recent record, if one exists | [
"",
"mysql",
"sql",
"join",
"relationship",
""
] |
I need to find anniversary date and anniversary year of employees and send email in every 14 days.But I have a problem with last week of December when using the following query if start date and end date are in different years.
```
Select * from Resource
where (DATEPART(dayofyear,JoinDate)
BETWEEN DATEPART... | Instead of comparing to a `dayofyear` (which resets to zero at jan 1st and is the reason your query breaks within 14 days of the end of the year) you could update the employee's `joindate` to be the current year for the purpose of the query and just compare to actual dates
```
Select * from Resource
-- Add the number ... | You could do this:
```
Select * from Resource
where DATEPART(dayofyear,JoinDate)
BETWEEN DATEPART(dayofyear,GETDATE())
AND DATEPART(dayofyear,DateAdd(DAY,14,GETDATE()))
OR
DATEPART(dayofyear,JoinDate)
BETWEEN (DATEPART(dayofyear,GETDATE()) + 365)
AND (DATEPART(dayofyear,DateAdd(DAY,14,GETDATE())) + 365)
``` | SQL query to find employee aniversary | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
We have a slave that follow the master. In near future, the master will shut down and the current slave will become new master.
After becoming master, how can I undo `CHANGE MASTER TO MASTER_HOST='master'...` SQL statement that previously executed on slave?
I can execute `STOP SLAVE;` but I curious to know how to ... | No need to UNDO change master info as it will not impact anything.
If you still want it for removing details then you can set all values with blank.
OR
remove master.info file and restart MySQL.
The direct command is:
```
RESET SLAVE;
```
In MySQL 8 and newer, `RESET SLAVE` has been deprecated. Use `RESET REPLICA` in... | I believe the command you are looking for is `RESET SLAVE`:
<https://dev.mysql.com/doc/refman/5.5/en/reset-slave.html> | how to undo CHANGE MASTER TO | [
"",
"mysql",
"sql",
"master-slave",
"percona",
""
] |
Input
```
+-------+---------+----------+
| Name | Country | State |
+-------+---------+----------+
| jon | US | Chicago |
+-------+---------+----------+
| kathy | US | CA |
+-------+---------+----------+
| linda | US | LA |
+-------+---------+----------+
| harry | UK | wales |... | SELECT country, COUNT(\*) as c FROM table b
GROUP BY country
ORDER BY c DESC LIMIT 1;
UPDATE: This should work
```
select state,count(*) c2 from a t1
INNER JOIN (
SELECT country, COUNT(*) as c FROM a t1 GROUP BY country ORDER BY c DESC LIMIT 1) t2 on t1.country = t2.country
GROUP BY state ORDER BY c2 DESC LIMIT 1
``` | Try this
```
select * from table e
where e.state in
(select d.state from table a
where a.country in
(SELECT country FROM table b
GROUP BY country
ORDER BY count(*) DESC LIMIT 1);
GROUP BY state
ORDER BY count(*) DESC LIMIT 1);
``` | Sub query to fetch the highest value | [
"",
"mysql",
"sql",
""
] |
I'm working on a SQL query like that :
```
PROC SQL;
CREATE TABLE WORK.test AS
SELECT
ARTICLES.sku,
ARTICLES.family_set,
ARTICLES.classe_article,
CASE
WHEN EXISTS (SELECT CATALOG_PAGE2 FROM ODS.ARTICLECOMPANY14 WHERE ODS_ARTICLECOMPANY14.ITEMNUM = ARTICLES.sku)
THEN "... | `proc sql` supports `exists`. I suspect the problem might be the double quotes:
```
PROC SQL;
CREATE TABLE WORK.test AS
SELECT a.sku, a.family_set, a.classe_article,
(CASE WHEN EXISTS (SELECT 1
FROM ODS.ARTICLECOMPANY14 oc
W... | Well I would suggest you to reform it to a `LEFT JOIN` and an `ISNULL` function:
```
SELECT ARTICLES.sku,
ARTICLES.family_set,
ARTICLES.classe_article,
COALESCE(ACompany.CATALOG_PAGE2,0) AS pag_cat_mega
FROM WORK.ARTICLES AS ARTICLES
LEFT JOIN ODS.ARTICLECOMPANY14 AS ACompany
ON ACompany.ITEMNUM =... | SQL CASE exist then value | [
"",
"sql",
"sas",
"case",
"exists",
"proc-sql",
""
] |
```
SELECT zlec_status.nazwa AS Status,
piorytet.nazwa AS Priorytet,
Concat(koord.imie, ' ', koord.nazwisko) AS `Koordynator`,
Concat(zlec_adresy.town, ' - ', zlec_adresy.street, ' ',
zlec_adresy.other)
... | Another, possibly more clean approach uses `OR`:
```
WHERE
town like concat('%',@userinput,'%')
OR
street like concat('%',@userinput,'%')
OR
other like concat('%',@userinput,'%')
``` | The query anatomy looks like this:
* it handles the `from`, because all the other clauses are dependent on it
* it handles the `where`, to filter out unneeded rows
* it handles the `select`, so you will get the columns you want
Note, that I did not mention `group by`, `having` or `order by`, since they are not part o... | Where statement that will use a concat | [
"",
"mysql",
"sql",
""
] |
I have a requirement where i have a select statement like below:
```
SELECT t1.a,t2.b,t2.c FROM t1,t2 WHERE t1.d = t2.e group by a,b;
```
I am fetching column `'b'` and grouping it with column `'a'`. However, the no of lines in table `t2` can be multiple for one count of column `t1.a` and `t2.b` can be different in e... | Thanks for the response guys,
The final answer that worked include the following logic:
```
decode(count(distinct prl.suggested_vendor_name) over (partition by prh.requisition_header_id),1,prl.suggested_vendor_name,0,null,'MULTIPLE')
vendor
```
I used `partition by` to group the vendors and `decode` to show the requ... | The closest approach i was able to find is the one stated down below. Just note that i've removed all the boilerplate you posted to improve readability.
```
select case
when vendors.vendorsqty > 1 then 'MULTIPLE'
else (select suggested_vendor_name
from po_requisition_lines_all
... | Combine a column in select statement if multiple data is present | [
"",
"sql",
"oracle",
"group-by",
""
] |
1. I have a table that specifies the current year (done in C#) `Years.Year`
2. I have a table called Weeks which contains the numbers (1-53) `Weeks.WeekNumber` <http://whatweekisit.org/>
Now from this I want to create a view which will list Monday's date of each week based upon the parameters `Years.Year` and `Weeks.W... | As mentioned in a comment, this is much easier if your build yourself a [calendar table](http://blog.jontav.com/post/9380766884/calendar-tables-are-incredibly-useful-in-sql), your query would simply be:
```
DECLARE @Year INT = 2015;
SELECT Date, ISOWeek
FROM CalendarTable
WHERE DayNumberOfWeek = 1
AND ISOYea... | You can write as:
```
-- SET DATEFIRST to U.S. English default value of 7.
SET DATEFIRST 7;
SELECT DATEPART( wk, [DateofYear]) as [Week Number],
[DateofYear] as[MondayDate]
FROM (
SELECT TOP (365)
DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY number)-1, '20150101') AS [DateofYear]
FROM [master].dbo.spt_values
WH... | SQL Server - Mondays date based on week number and year (view) | [
"",
"sql",
"sql-server",
""
] |
I was trying to figure out how to insert the data to the second table from the first table, but I don't want to insert the existing data that the second table already had from previous injection. Is there any way to check before it inserts the data?
**Here is what I have so far:**
```
INSERT INTO content2 (d1, d2, d3... | You can have the database verify that the data is unique. For instance, if the triple of `d1, d2, d3` is supposed to be unique, then create a unique index/constraint on those columns:
```
create unique index idx_content2_d1_d2_d3 on content2(d1, d2, d3);
```
Then if you try to insert a row, you'll get an error. You c... | ```
INSERT INTO content2 (d1,d2,d3)
SELECT c1.d1,c1.d2,c1.d3 from content c1
Where not exists (
select *
from content2 as c2
where c1.d1 = c2.d1 and c1.d2 = c2.d2 and c1.d3 = c2.d3
)
```
Hope this will help
[Fiddle for selecting the row from c1 which not exist in c2](http://sqlfiddle.com/#!9... | Only insert the data from the first table that doesn't exist in the second table | [
"",
"mysql",
"sql",
""
] |
I've created a table with a computed column as the primary key.
Table is created fine.And here is the script..
```
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ARITHABORT ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [planning.A062].[RMAllocation](
[Id] [int] IDENTITY(100,1) NOT NULL,
[RMAllocatonId] ... | Something is wrong with the designer. SQL Server is quite clear in the documentation that computed columns *can* be used for primary keys (for instance, [here](https://msdn.microsoft.com/en-us/library/ms191250(v=sql.105).aspx)).
My guess is that the designer is dropping all constraints on the table and adding them bac... | According to [the documentation](https://msdn.microsoft.com/en-us/library/ms188300.aspx) (emphasis mine)
> A computed column cannot be used as a DEFAULT or FOREIGN KEY
> constraint definition **or with a NOT NULL constraint definition**.
So it may be somewhat surprising that it works at all even in TSQL.
When the de... | SQL Server Computed Column as Primary Key | [
"",
"sql",
"sql-server",
""
] |
I'm trying to fetch a PLSQL statement to display all the list of customer ID and the sum of order value for each customer. the following code gets me the correct answer but the issue is that I have multiple customers with the same ID and I need to sum all their order values under only 1 ID output and not multiple.my co... | You just need to use **SUM** as aggregate function using **GROUP BY**.
Using **PL/SQL**
```
SQL> SET serveroutput ON
SQL> DECLARE
2 CURSOR cur
3 IS
4 SELECT SUM(sales.quantity),
5 SUM(products.price),
6 sales.customer_ID
7 FROM sales,
8 products
9 WHERE sales.... | Try this
```
SELECT CUSTOMER_ID
,SUM(QUANTITY) as Total_Quantity
,SUM(QUANTITY*PRICE) as Total_Price
FROM
SALES s INNER JOIN
PRODUCTS p on p.PRODUCT_ID=s.PRODUCT_ID
GROUP BY CUSTOMER_ID // Group By each customer Id.
``` | sum of total values PL/Sql | [
"",
"sql",
"oracle",
"plsql",
""
] |
I'm a self-taught, vaguely competent SQL user. For a view that I'm writing, I'm trying to develop a 'conditional `LEFT`' string-splitting command (presumably later to be joined by a 'conditional `RIGHT`' - whereby:
* If a string (let's call it 'haystack') contains a particular pattern (let's call it 'needle'), **it wi... | There are two parts to this problem, the first is the nature of the `ISNULL` operator, it will use the datatype and length of the first argument. A simple example would be:
```
DECLARE @A CHAR(1) = NULL,
@B VARCHAR(MAX) = 'This is a test';
SELECT TOP 1 Test = ISNULL(@A, @B);
```
This returns `T` and checkin... | This is the difference between `isnull` and `coalesce` -- and since your first parameter to isnull is char(1), that will be the type of return value of the statement. With coalesce you'll get the correct result.
[Isnull](https://msdn.microsoft.com/en-us/library/ms184325.aspx):
Returns the same type as check\_expressi... | SQL Server : ISNULL(compound NULL condition, 'a string') returns only the 1st character, under certain circumstance(s) | [
"",
"sql",
"sql-server",
"string",
"isnull",
"nullif",
""
] |
I'm using SQL Server management studio 2008 and use `TOP` to select some data from DB.
```
SELECT
TOP 3 Name, Company, ta_Content, Email, Writedate
FROM dbo.ta_CONTACT
WHERE Name in ('David', 'Filo', 'Rain', 'Cone', 'Source', 'Tailor', 'Fier', 'Venesse')
ORDER BY Writedate;
```
So by using `TOP 3`, I can collect... | Try this query:
```
SELECT * FROM (
SELECT ROW_NUMBER() OVER (ORDER BY Writedate ASC) AS rownumber,
Name, Company, ta_Content, Email, Writedate
FROM dbo.ta_CONTACT
) AS t
WHERE rownumber >= 5 AND rownumber <= 7
``` | Try this query.It is not right way.
```
select TOP 2 Name, Company, ta_Content, Email, Writedate from (
SELECT TOP 3 Name, Company, ta_Content, Email, Writedate FROM dbo.ta_CONTACT
WHERE Name in ('David', 'Filo', 'Rain', 'Cone', 'Source', 'Tailor', 'Fier', 'Venesse')
ORDER BY Writedate desc)a ORDER BY Writedate
``` | Selecting some row numbers from SQL | [
"",
"sql",
"sql-server",
""
] |
Can anyone help me to find out below format using `Convert` function in SQL Server?
DateTime
```
yyyy/MM/dd hhmm
yyyy/MM/dd hhmmssstt
```
Time
```
hh:mm
hh:mm:ss tt
hh:mm tt
```
Thanks in advance... | I am unable to get exact format which i need with Convert() so i am using Format() now.
Also want to say Format() is poor performance compare to Convert(). | [This MSDN page here](https://msdn.microsoft.com/en-us/library/ms187928.aspx) lists all available "styles" for conversion.
If you're using SQL Server **2012** or newer, you can also look [at the new `FORMAT` function](https://msdn.microsoft.com/en-us/library/hh213505.aspx) for even more flexibility | Convert DateTime Format using Convert function in SQL Server | [
"",
"sql",
"sql-server",
"datetime",
""
] |
I have a query:
```
SELECT * FROM (SELECT col1,col2,col3,ROWNUM R
FROM TBL WHERE ROWNUM < 3)
WHERE R='2';
```
(rownum will change each time giving only one record at a time )
```
column1 column2 column3
alpha beta gamma
```
I need result as:
```
alpha,beta,... | There are two ways:
**CONCAT** function
```
SELECT *
FROM
(SELECT concat(concat(concat(concat('a', ','), col2), ','), col3),
ROWNUM R
FROM TBL
WHERE ROWNUM < 3
)
WHERE R=2;
```
`||` concatenation operator
```
SELECT *
FROM
(SELECT col1||','||col2||','||col3,ROWNUM R FROM TBL WHERE ROWNUM < 3
)
WHERE... | You can use following:-
```
SELECT *
FROM (SELECT col1||','||col2||','||col3,ROWNUM R
FROM TBL WHERE ROWNUM < 3)
WHERE R='2';
``` | concat result of sql query using field seperator | [
"",
"sql",
"oracle",
"oracle11g",
""
] |
I have lists like this stored in a field in SQL:
```
Id MyListField
1 soy, meat, milk, wheat, nuts
2 soy, meat, nuts, milk, wheat
3 nuts
4 walnuts, nutshell, nuts
5 nuts, beans
6 walnuts, hazel nuts
7 nutshell, nutsize
```
**This is not normalized and I can't change it.** I now have to find `nuts` and replace ... | If you concatenate the field between `,` and `_,` then you only have one case to look for.
e.g.
```
update MyTable set MyFieldList = replace(', ' + MyFieldList + ',', ', nuts,', ', insane,')
update MyTable set MyFieldList = substring(MyFieldList, 3, len(MyFieldList) - 3)
``` | By putting a comma at the start and end of the list, each element is wrapped in a leading ", " and a trailing ",".
Then your replace method becomes easy....
```
REPLACE(', ' + MyListField + ',',
', ' + @termToReplace + ',',
', ' + @replacement + ',')
```
Finally, strip the leading and trailing... | Find value in comma-separated list | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I am trying to return a minimum `fiscalyear` with a grouping on `productid` using a subquery and the `EXISTS` operator. For whatever reason, I am getting an arbitrary value from a set of fiscal years. The subquery returns the minimum `fiscalyear` but the outer query won't pick it up for the `UPDATE`. Any ideas?
```
UP... | You don't need the join's *outside* the exists. In addition, I assume you are using SQL Server.
Actually, I don't think you want `exists` at all. Just use `=` like this:
```
UPDATE t
SET SALES_YEAR = sa.fiscalyear
FROM #Temp t
WHERE t.product_id = (Select TOP 1 sa.productid
FROM sales sa JOI... | try this query
```
UPDATE #Temp
SET SALES_YEAR = A.fiscalyear
FROM #Temp t
JOIN (
select MIN(sa.fiscalyear),
sa.productid
FROM sales sa
JOIN products p ON p.id = sa.productid
JOIN #Temp t ON p.id = t.productid
GROUP BY sa.productid
) A ON T.PRODUCTID=A.PRODUCTID
``` | Bad value returned using EXISTS | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am currently using BigQuery and GROUP\_CONCAT which works perfectly fine. However, when I try to add a ORDER BY clause to the GROUP\_CONCAT statement like I would do in SQL, I receive an error.
So e.g., something like
`SELECT a, GROUP_CONCAT(b ORDER BY c)
FROM test
GROUP BY a`
The same happens if I try to specify ... | Since BigQuery doesn't support ORDER BY clause inside GROUP\_CONCAT function, this functionality can be achieved by use of analytic window functions. And in BigQuery separator for GROUP\_CONCAT is simply a second parameter for the function.
Below example illustrates this:
```
select key, first(grouped_value) concat_va... | Standard SQL mode in BigQuery does support ORDER BY clause within some aggregate functions, including STRING\_AGG, for example:
```
#standardSQL
select string_agg(t.x order by t.y)
from unnest([struct<x STRING, y INT64>('a', 5), ('b', 1), ('c', 10)]) t
```
will result in
`b,a,c`
Documentation is here: <https://clo... | BigQuery GROUP_CONCAT and ORDER BY | [
"",
"sql",
"google-bigquery",
""
] |
How to extract only Email Id from the below example (i.e. abc@abc.com, mno@mno.com, etc.)? Each row can contains multiple Email IDs...
```
"ABC" <abc@abc.com>; "XYZ" <xyz@xyz.com>; pqr@pqr.com; "MNO" <mno@mno.com>
``` | In *MySQL* you could use `SUBSTRING_INDEX` in following:
```
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(Id, '>', 1), '<', -1) Email
FROM Tbl;
```
In *SQL Server* will be:
```
SELECT SUBSTRING(Id, CHARINDEX('<', Id) + 1 , CHARINDEX('>', Id) - CHARINDEX('<', Id) - 1)
FROM Tbl;
``` | ```
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(email,'>',1),'<',-1) AS EmailID
FROM table_name;
``` | How to Extract only email id in SQL SERVER | [
"",
"sql",
"sql-server",
""
] |
I want to select 1000 rows at a time using the query:
```
SELECT * FROM MEMBERID_1M WHERE ROWNUM <1000
```
How do I get the next set of 1000 rows from this table in a for loop? | I suggest you to use `ROW_NUMBER()` function like this: (my `id` is your PK)
```
SELECT M.*
FROM (
SELECT MEMBERID_1M.*, ROW_NUMBER() OVER (ORDER BY id) As rn
FROM MEMBERID_1M ) M
WHERE
(rn <= 1000)
```
And for next:
```
SELECT M.*
FROM (
SELECT MEMBERID_1M.*, ROW_NUMBER() OVER (ORDER BY id) As rn... | Reproducing the [answer](https://stackoverflow.com/questions/3869311/sql-oracle-to-select-the-first-10-records-then-the-next-10-and-so-on)
There is only a rather convoluted way to do this, which is a real pain with Oracle. They should just implement a LIMIT/OFFSET clause...
The rownum gets assigned *after* the row ha... | Get 1000 row set from Oracle table | [
"",
"sql",
"oracle",
"select",
""
] |
In **PostgreSQL 9.4** the window functions have the new option of a `FILTER` to select a sub-set of the window frame for processing. The documentation mentions it, but provides no sample. An online search yields some samples, including from [2ndQuadrant](http://blog.2ndquadrant.com/the-within-group-and-filter-sql-claus... | You are not actually *aggregating* rows, so the new aggregate `FILTER` clause is not the right tool. A window function is more like it, a problem remains, however: the **[frame definition](http://www.postgresql.org/docs/current/interactive/sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS)** of a window cannot depend on *va... | I don't think there is any syntax that means "current row" in an expression. The gram.y file for postgres makes a filter clause
take just an a\_expr, which is just the normal expression clauses. There
is nothing specific to window functions or filter clauses in an expression.
As far as I can find, the only current row ... | Referencing current row in FILTER clause of window function | [
"",
"sql",
"postgresql",
"window-functions",
"postgresql-9.4",
""
] |
I'd like a column of numbers:
Seven occurances of the integer 1, followed by 7 occurances of 2, followed by 7 occurances of 3 .... , followed by 7 occurances of n-1, followed by 7 occurances of n. Like so
```
Num
1
1
1
1
1
1
1
2
2
2
2
2
2
2
...
...
n-1
n-1
n-1
n-1
n-1
n-1
n-1
n
n
n
n
n
n
n
```
Unfortunately I've not ... | ```
;WITH Numbers AS
(
SELECT n = 1
UNION ALL
SELECT n + 1
FROM Numbers
WHERE n+1 <= 10
),
se7en AS
(
SELECT n = 1
UNION ALL
SELECT n + 1
FROM se7en
WHERE n+1 <= 7
)
SELECT Numbers.n
FROM Numbers CROSS JOIN se7en
``` | ```
WITH t1 AS (SELECT 0 as num UNION ALL SELECT 0)
,t2 AS (SELECT 0 as num FROM t1 as a CROSS JOIN t1 as b)
,t3 AS (SELECT 0 as num FROM t2 as a CROSS JOIN t2 as b)
,t4 AS (SELECT 0 as num FROM t3 as a CROSS JOIN t3 as b)
,Tally (number)
AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) FROM t4... | Recursive cte to repeat several integers | [
"",
"sql",
"t-sql",
"sql-server-2012",
""
] |
I'm trying to combine data from two tables in one result. With simplified example-tables, this is what I want to get in result:
```
ID Text Choice
--------------------------------
1 My first choice 0
2 My second choice 0
3 My third choice 1
```
from the two tables persons and ... | You can try the next query
```
SELECT Choices.*
,IF(Choices_made.Choice_ID IS NULL, 0, 1) AS Choice
FROM Choices
LEFT JOIN Choices_made ON Choices_made.Choice_ID = Choices.ID AND Choices_made.Person_ID = @PersonID
``` | ```
SELECT c.id,
c.text,
cm.Choice_ID = c.id as persons_choice
FROM Choices c
LEFT JOIN Choices_made cm on cm.Choice_ID = c.id
and cm.Person_ID = 2
``` | SQL - Combine a select * query with select 1 | [
"",
"mysql",
"sql",
"select",
""
] |
Within my SQL database I have a table which represents books of tickets [Books] where the number of tickets within a book can vary.
This is represented by two columns `[Books].[StartNo]` and `[Books].[BookSize]`
What I need to achieve is a select statement that repeats each row in the table [Books] for each ticket in... | Use `tally table`
```
WITH lv0 AS (SELECT 0 g UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0 UNION ALL SELECT 0)
,lv1 AS (SELECT 0 g FROM lv0 a CROSS JOIN lv0 b) --10 * 10 = 100
,lv2 AS (SELECT 0 g FROM lv... | Try this:
```
;WITH Counts AS (
SELECT Max(StartNo + BookSize) AS TotalBookSize
FROM t
), CTE(Tickets) AS (
SELECT 1
UNION ALL
SELECT Tickets + 1
FROM CTE
WHERE Tickets < (SELECT TotalBookSize FROM Counts)
)
SELECT *
FROM t JOIN CTE ON CTE.Tickets BETWEEN t.StartNo AND t.StartNo + t.BookSiz... | Expand header row into multiple child rows | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I have two tables, each with the same schema.
The first one (or `OldDataTable` from here on) looks like this:
```
| PlantID | OutletId | BusinessTypeID | TradeChannelID |
|---------|-----------|----------------|----------------|
| I000 | 500113730 | 1 | 8 |
| I000 | 500113772 | ... | It should be easy enough to join the two tables together, using a constraint that checks for anything different:
```
SELECT
old.PlantID
,old.OutletID
,old.BusinessTypeID
,new.BusinessTypeID AS Change_BusinessTypeID
,old.TradeChannelID
,new.TradeChannelID AS Change_TradeChannelID
FROM
OldDat... | Here's a simple version for you. You can change the CASE statement(s) as you need to to benefit what output you wish (e.g. use bit fields, etc)... If you wish to return all rows, changed or not, just REM out the WHERE clause.
Hope it assists,
```
DECLARE @OldDataTable AS TABLE (PlantID nvarchar(20), OutletId nvarchar... | Finding the differences between tables with same schema, with changes and original values in same output | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a table like this in MySQL:
```
+-----+------+
| id | type |
+-----+------+
| 149 | 8 |
| 150 | 7 |
| 151 | 8 |
| 152 | 7 |
| 153 | 5 |
| 154 | 6 |
| 155 | 3 |
| 156 | 2 |
| 157 | 4 |
| 158 | 2 |
| 159 | 1 |
| 160 | 0 |
+-----+------+
```
I would like to sort this table and... | ```
SELECT id, TYPE FROM (
SELECT id, TYPE,
IF(@myvar = 0 OR @myvar = TYPE, @counter := @counter + 1, @counter := 1) sequence,
@myvar := TYPE FROM mytable
JOIN (SELECT @myvar := 0, @counter := 0 ) a
ORDER BY TYPE DESC, id) b
ORDER BY sequence, TYPE DESC, id
```
This query will work for any level.... | This will work only if frequency of type is **two**.
Write following code in procedure:
```
drop temporary table if exists tmp;
create temporary table tmp
select min(id) as min_id ,max(id) as max_id from table_name group by type;
select * from table_name where id in( select max_id from tmp) order by type
union all
... | mysql advanced order by query | [
"",
"mysql",
"sql",
""
] |
How can I compare just the dates of timestamps while ignoring the times?
I just want to compare the month/date/year. For example:
```
select * from Batch
where openingtime <> closingtime
```
The problem is that this will show too many batches, since it will include batches where `OpeningTime` and `ClosingTime` diffe... | cast both timestamps as dates
For SQL Server
```
Select *
from Batch
where cast(openingtime as date) <> cast(closingtime as date)
```
For Oracle
```
Select *
from Batch
where trunc(openingtime) <> trunc(closingtime)
``` | Another way
```
Select * from Batch where
CONVERT(VARCHAR(10),openingtime,110<>CONVERT(VARCHAR(10),closingtime,110)
``` | SQL: How to compare dates while ignoring the time? | [
"",
"sql",
""
] |
I use this query to get all the stored procedure in my database (I'm using Microsoft SQL Server 2008):
```
SELECT
SPECIFIC_NAME, ROUTINE_DEFINITION
FROM
INFORMATION_SCHEMA.ROUTINES
```
For almost all result everything is ok, but for the row with a very long `ROUTINE_DEFINITION` the result is cropped.
Do... | Please try with `sp_helptext 'ProcedureName'` or you can use either `sys.sql_modules` or `OBJECT_DEFINITION([object_id])` function to get the stored procedure text.
All this gives your exact code. `Information_Schema.Routines` will give up to max of nvarchar(4000). | If you are using SQL Server Management Studio then it is possible that it does not display all of the text of the stored procedure (since I believe [there is a 8192 character limit for each column](https://msdn.microsoft.com/en-us/library/ms178782(v=sql.100))).
One thing you can do to check this is to verify the lengt... | SQL query to get Stored Procedure crop result if the routine_definition is greater than 4000 char | [
"",
"sql",
"sql-server",
""
] |
I have two tables:
```
User : (id, username, created_at, updated_at)
Comment : (comment_id, user_id, username, created_at, updated_at)
```
Note: **yes, I do understand Comment table has a duplicated field, 'username'. However, the table is already designed in that way and I have no permission to redesign the sche... | Neither has solved the issue.... :'(
```
SELECT
*,
(SELECT COUNT(id) FROM Comment WHERE id = id) AS Comments
FROM User
ORDER BY id DESC
```
This work-around has solved the issue... it's a simplified version of what i've actually coded tho. I still appreciate your answers. | ```
SELECT u.id, u.username, COUNT(c.id) as theCount
FROM User u
JOIN Comment c ON u.id = c.id
GROUP BY u.id,u.username
``` | Select users' info with their total number of comments | [
"",
"sql",
"sql-server",
""
] |
Using the Linq fluent syntax, how do I get the contents of table1 using a foreign key from table 2. For example given tables
```
tblPropertyExtras tblExtra
PropertyExtraId ExtraId
propertyId ExtraName
ExtraId
```
I am trying to do the equivalent of the SQL
```
Select tblExtra.*
From tblPr... | This should work for you:-
```
var result = db.tblPropertyExtras.Join(db.tblExtra,
pe => pe.ExtraId,
e => e.ExtraId,
(pe, e) => new { pe, e })
.Where(x => x.pe.propertyI... | ```
var query =
from p in tblPropertyExtras
where p.propertyId == 1234
select p.tblExtras;
```
If the Database has been mapped properly you should just be able to go `Entity.ForeignEntities`.
Fluent Linq is usually in the order of:
```
from
where
order
select
``` | Fluent Linq: Get he contents of Table1 where entry in Table2 | [
"",
"sql",
"linq",
""
] |
I am trying to return data in fifteen minute intervals. The first thing I thought to do was this:
`select * from myTable where DATEPART(minute, Timestamp) % 15 = 0`
But there are two problems with this approach. The first is that there will not necessarily always be data with a timestamp at a given minute, the other ... | Given a fixed start time, all you would need is a table of numbers to add your intervals to. If you don't already have a table of numbers (which are useful) then a quick way to generate one on the fly is
```
WITH N1 AS (SELECT N FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) t (N)),
N2 (N) AS (SELECT 1 FROM N1 ... | Like Shnugo mention, you can use a tally table to get your data in an interval of 15 minutes, something like this.
I am creating a dynamic tally table using CTE however you can even use a physical calendar table as per your needs.
```
DECLARE @StartTime DATETIME = '2015-01-01 00:00:00',@EndTime DATETIME = '2015-01-01... | How to return value based on the last available timestamp if the exact time is unavailable? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2014",
""
] |
This is my table structure
```
CUST_ID ORDER_DT
1 01-2013
1 04-2013
1 01-2015
1 02-2015
```
What I am trying to achieve is classify the customer as new customer/existing customer and revived.
Logic is
First time order- New
Time from last purchase within 365 days then Existing
Time more th... | The idea way would be to use `lag()`. Teradata doesn't quite support lag, but it does support other window functions. So, you can mimic it:
```
select t.cust_id, t.order_dt,
(case when order_dt - prev_od <= 365 then 'Existing' else 'New'
end) as flag
from (select t.*,
max(order_dt) over (pa... | This includes the "revived" logic which was missing in Gordon's answer:
```
SELECT
CUST_ID, ORDER_DT,
CASE
WHEN ORDER_DT = MIN(ORDER_DT) -- first order
OVER (PARTITION BY CUST_ID)
THEN 'New'
WHEN ORDER_DT >= MAX(ORDER_DT) -- more than 365 days since previous order
... | SQL nested logic | [
"",
"sql",
"logic",
"teradata",
""
] |
I have large number of open files limit in MySQL.
I have set **open\_files\_limit** to **150000** but still MySQL uses almost **80%** of it.
Also I have low traffic and max concurrent connections around 30 and no query has more than 4 joins. | The files opened by the server are visible in the performance\_schema.
See table performance\_schema.file\_instances.
<http://dev.mysql.com/doc/refman/5.5/en/file-instances-table.html>
As for tracing which query opens which file, it does not work that way, due to caching in the server itself (table cache, table defi... | MySQL shouldn't open that many files, unless you have set a ludicrously large value for the `table_cache` parameter (the default is 64, the maximum is 512K).
You can reduce the number of open files by issuing the `FLUSH TABLES` command.
Otherwise, the appropriate value of `table_cache` can be roughly estimated (in Li... | Is it possible to check that a particular query opens how many files in MySQL? | [
"",
"mysql",
"sql",
"linux",
"database",
"mysql-5.5",
""
] |
```
Some_Column (Table ABC)
___
123
456
NULL
789
```
When I run `SELECT * FROM ABC` it returns all rows.
However, when I run
`SELECT * FROM ABC WHERE Some_Column <> ''`
it returns all the values but the null. Whether `ANSI_NULLS` is on or off.
Can anyone explain this peculiar behavior to me? | It's by design. From [the doc](https://msdn.microsoft.com/en-us/library/ms188048(v=sql.100).aspx) (emphasis mine):
> When SET ANSI\_NULLS is OFF, the Equals (=) and Not Equal To (<>) comparison operators do not follow the ISO standard. A SELECT statement that uses WHERE column\_name = NULL returns the rows that have n... | This happens because NULL is neither equal to, nor unequal to ''...NULL is simply the absence of a value. You could claim it is 'unknown'.
The only way of including NULLs in the return of your query is to add a clause to check for null values:-
```
SELECT * FROM ABC WHERE Some_Column <> '' OR Some_Column IS NOT NULL
... | Comparison with NULL behavior the same even when setting ANSI_NULLS | [
"",
"sql",
"sql-server-2008",
""
] |
I believe what I'm asking here is possible, but I haven't find a way yet :
Some cells in the result of my SQL *SELECT-FROM-WHERE* query are blank, and in DbVisualizer, `(null)` is written inside. I'd like to display a blank cell instead.
I've already tried with *CASE-WHEN* and the *NVL* operator, but it won't let me... | The problem in your query is the following **ELSE** part of the **CASE** expression:
> ```
> ELSE
> ''
> ```
In *Oracle*, an **empty string** is considered as **NULL** value. So, all you need to do is use *something* else instead of `''`.
For example, to use a **space** instead of **NULL**:
```
ELSE
' '
`... | Did you try *standard* SQL function [coalesce()](http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm), as below ?
```
SELECT COALESCE(columnName, '') AS ColumnName FROM tableName;
```
---
**Syntax:**

```
COALESCE (expr1, expr2)
```
is equi... | Replacing "(null)" with blank cell in SQL query result | [
"",
"sql",
"string",
"oracle",
"null",
"dbvisualizer",
""
] |
I´m creating a data model to register the SERVICES that an EMPLOYEE is able to perform based on its list of COURSES completed (COURSE\_ID). To do this I have two data tables: EMPLOYEES and SERVICES. And I have two map tables: one table to relate the COURSES completed by EMPLOYEE and another table to relate the COURSES ... | Here is how I would do it:
```
with employees as (select 1 emp_id, 'Joe' name from dual union all
select 2 emp_id, 'Bob' name from dual union all
select 3 emp_id, 'Rob' name from dual),
services as (select 1 serv_id, 'Install' service from dual union all
... | Just start joining tables.
```
select yourfields
from employees join employee_courses using (emp_id)
join service_courses using (course_id)
join services using (serv_id)
etc
``` | How to create a query to compare two exact results of two additional queries? | [
"",
"sql",
"oracle",
""
] |
How can I perform a query with multiple LIKE parameters?
For example, I have this string to search through:
```
"I like searching very much"
```
This is the code I currently use:
```
$searTerm = "like"
$this->db->or_like('list.description', $SearchTerm,'both');
```
But i want to search with 2 or 3 parameters. like... | You can simply repeat the `like` parameters on the active record. In your example you would do something like this:
```
$this->db->or_like('list.description', $searchTerm1);
$this->db->or_like('list.description', $searchTerm2);
$this->db->or_like('list.description', $searchTerm3);
...
```
This will just join each `or... | Firstly, you need to define the array with like variables then, its very important to put the `or_like` statement above the `where` clause in order to make multiple 'OR' statements for `like` 'AND' the where clause.
Here is example:
```
$this->db->or_like(array('column_name1' => $k, 'column_name2' => $k))
$this->db->... | Codeigniter database queries with multiple LIKE parameters | [
"",
"sql",
"codeigniter",
""
] |
I need help with SQL for generating pivot table with row/column totals calculated ..I have 2 tables as given below
```
Table ProbCat
==============
probcat | probdesc
1 minor
2 high
3 showstopper
Table ProbSummary
===================
prodcat | noofproblems | stage
1 5 Dev... | Just like others mentioned, your summary/total calculation should be done on the presentation layer. But here is my attempt to getting your output minus the last summary line:
```
;WITH Q1
AS (
SELECT pvt.probcat
,pvt.probdesc
,ISNULL(pvt.[Dev], 0) AS 'Dev'
,ISNULL(pvt.[QA], 0) AS 'QA'
... | ```
with x as
(select p.probcat as probcategory, p.probdesc as categotydesc,
case when s.stage = 'Dev' and s.noofproblems > 0 then s.noofproblems else 0 end as Dev,
case when s.stage = 'QA' and s.noofproblems > 0 then s.noofproblems else 0 end as QA,
case when s.stage = 'Prod' and s.noofproblems > 0 then s.noofproblems... | Summary table with row/column totals using SQL pivot | [
"",
"sql",
"sql-server",
"pivot",
"pivot-table",
""
] |
I want to select all the customers that have the same name and birth date on mysql table.
my query right now is close, but it seems to have a flaw:
```
SELECT
id,
customer.name,
date
FROM
customer
INNER JOIN (
SELECT
name
FROM
customer
GROUP BY
name,date
HAVING
... | Return a customer if there `EXISTS` another one with same name and date, but other id:
```
SELECT
id,
name,
date
FROM
customer c1
where exists (SELECT 1 from customer c2
where c2.name = c1.name
and c2.date = c1.date
and c2.id <> c1.id)
```
`JOIN` version:
... | Something like this should do it:
```
select
c1.*
from
customer c1
join customer c2 on
c1.name = c2.name
and c1.birth_date = c2.birth_date
and c1.id != c2.id
order by name, birth_date, id
;
```
And here's the full example:
```
drop table customer;
create table customer (
... | Select All customers with exact name and birthdate | [
"",
"mysql",
"sql",
""
] |
I have data that was sent to me, and I need to normalize it. The data is in a sql table, but each row has multiple multi value columns. An example is the following:
```
ID fname lname projects projdates
1 John Doe projA;projB;projC 20150701;20150801;20150901
2 Jane Smith pro... | If you use Jeff Moden's "[DelimitedSplit8K](http://www.sqlservercentral.com/articles/Tally+Table/72993/)" splitter (Which I have renamed here "fDelimitedSplit8K")
(Ref. Figure 21: *The Final "New" Splitter Code, Ready for Testing*)
to do the heavy lifting for the splits, the rest becomes fairly straightforward, usin... | Try with this following query.
SELECT A.ID ,a.fname,a.lname ,a.projects ,
ltrim(Split.a.value('.', 'VARCHAR(100)')) AS projdates
FROM (SELECT ID , fname, lname , projects,
CAST ('' + REPLACE([projdates], ';', '') + '' AS XML) AS String
FROM ) AS A CROSS APPLY String.nodes ('/M') AS Split(a);
Try with this you wil... | SQL Split Multiple Multivalue Columns into Rows | [
"",
"sql",
"parsing",
"split",
"multivalue",
""
] |
I have three tables: `comics`, `tags` and `comicTags`.
The `comics` table ID is connected through a foreign key with the `comicTags` table while the `tags` table ID is also connected to the `comicTags` table through the `tagID`.
```
comics table
+----+
| ID |
+----+
| 1 |
| 2 |
+----+
comicTags table
+---------+-... | You need to search for rows where the tag\_id is one of the tags you are looking for, and then ensure that the number of rows returned is equal to the number of tags, like this:
```
SELECT c.id
FROM comics c
JOIN comicTags ct ON ct.comicID = c.id
JOIN tags t ON t.id = ct.tagID AND t.tag IN ('tag1', 'tag2')
GROUP BY c.... | you can run one query per "tag" you are looking for and then join the result:
```
select c.*
from
(
SELECT comicID
FROM tags t JOIN comicTags AS ct ON ct.tagID=t.ID
WHERE (t.tag LIKE 'tag1')
) a join
(
SELECT comicID
FROM tags t
JOIN comicTags AS ct ON ct.tagID=t.ID
WHERE (t.tag LIKE... | Get result with matching all search queries | [
"",
"mysql",
"sql",
""
] |
I have a SQL Server 2014 database with 2 fields:
- one of type `date` for the record date
- one of type `time` for the record time.
I want to retrieve records from the table between 2 dates/ times.
Example: from 2015-01-01 at 16:00 until 2015-01-02 at 08:00.
I tried
```
SELECT...
Date BETWEEN '2015-01-01' AND '2015-... | Try adding the fields:
```
WHERE cast(date as datetime)+cast(time as datetime) between
'2015-01-01 16:00' AND '2015-01-02 8:00'
``` | Your query will only work if want to find records within a certain time window between certain days. E.g. during office hours between 13 and 17 July.
```
WHERE [Date] BETWEEN '2015-07-13' AND '2015-07-17'
AND CONVERT(Time, [Time]) BETWEEN '08:00' AND '16:00'
```
And since your start `Time` value is greater than your ... | SQL query between date/time with different fileds for date and times | [
"",
"sql",
"sql-server",
"date",
"datetime",
"time",
""
] |
Lets say I use `coalesce()` to combine two columns into one in select and subsequently a view constructed around such select.
Tables:
```
values_int
id INTEGER(11) PRIMARY KEY
value INTEGER(11)
values_varchar
id INTEGER(11) PRIMARY KEY
value VARCHAR(255)
vals
id INTEGER(11) PRIMARY KEY
value INTEGER(11) //foreign k... | You query should be explicit to be clear, In this case mysql is using varchar.
I would write this query like this to be clear
```
coalesce(values_int.value,cast(values_varchar.value as integer), 0)
```
or
```
coalesce(cast(values_int.value as varchar(20)),values_varchar.value,'0')
```
you should put in that last v... | Returns the data type of expression with the highest data type precedence. If all expressions are nonnullable, the result is typed as nonnullable.
So in your case the type will be `VARCHAR(255)` | SQL coalesce(): what type does the combined column have? | [
"",
"mysql",
"sql",
"coalesce",
""
] |
I have an SQL table with two text columns and I'd like find the number of words in each of those and also the number of common words.
Basically a word should be the regex `[A-Za-z]{3,}` (at least 3 chars) and for a row with the values `left="abc def ghi"` and `right="ghi abc qwe rtz"` the result should be `wordsleft=3... | So, even though SQL might not be the best option to do something like this (it's probably a lot easier using a scripting language) you can do it using common table expressions with `connect by` queries to split the strings into rows and then count the number of distinct items in each column (and the common items).
Giv... | SQL is an excellent tool for this. Using jpw's dataset and the OP's requirement that words be 3+ characters in length:
```
with t1(id, l, r) as (
select 1, 'abc def ghi', 'ghi abc qwe rtz' from dual union all
select 2, 'bc de gh', 'gh ab qw rt xx' from dual union all
select 3, 'xbc de gh yy', 'gh xbc' from dual
... | Find number of common words in SQL table columns? | [
"",
"sql",
"oracle",
""
] |
```
**Table1** **Table2**
ID Values ID Values
1 100 1 10
2 200 2 20
3 300 3 30
4 400 4 40
null 2000 null 3000
5 500
```
o/p:-
`... | Try this ..
```
select t1.id,t1.values,t2.values from
table1 t1
left outer join
table t2 on nvl(t1.id,0)=nvl(t2.id,0)
``` | You can add a check to see if both values are `NULL` to the join condition:
```
SELECT t1.ID,
t1.VALUES AS Table1Values,
t2.VALUES AS Table2Values
FROM TABLE2 t1
LEFT OUTER JOIN
TABLE2 t2
ON ( t1.ID = t2.ID OR ( t1.ID IS NULL AND t2.ID IS NULL ) )
``` | left outer join with null values | [
"",
"sql",
"oracle",
""
] |
I have the following table structure (and data example):
```
id code category
1 x c1
1 y c1
1 a c2
2 y c1
2 a c2
3 a c2
4 j c3
```
Given a list of pairs <(category, code)>, one for each category, I need to query the `ids` which match the pairs. The rule is: if a category is... | I would do it like here:
```
with input(cat, code) as (select 'c1', 'x' from dual
union all select 'c2', 'a' from dual
union all select 'c3', 'k' from dual)
select id from (
select t.id, max(decode(i.code, t.code, 1, 0)) cc from t
left join input i on i.cat = t.cat and i.code = t... | Made it work with the following query:
```
select distinct t2.ID from t t2
where
( not exists (select * from t where id = t2.id and cat like 'c2')
or (exists ( select * from t where id = t2.id and cat = 'c2' and code = 'a')))
and
(not exists (select * from t where id = t2.id and cat like 'c1')
or (exists( select * f... | SQL Query which depends on the existence of other rows | [
"",
"sql",
"oracle",
""
] |
I have a text memo field in SQL table that I need to remove the last character in the field if it's a comma.
So, for example, if I have these rows, I need to remove the commas from rows 2 and 4.
```
INETSHORTD
1 94
2 85,
3 94, 92
4 89, 99, 32,
```
The output would be:
```
INETSHORTD
94
85
94, 92
89,... | Using `REVERSE` and `STUFF`:
```
SELECT
REVERSE(
STUFF(
REVERSE(LTRIM(RTRIM(INETSHORTD))),
1,
CASE WHEN SUBSTRING((REVERSE(LTRIM(RTRIM(INETSHORTD)))), 1, 1) = ',' THEN 1 ELSE 0 END,
''
)
)
FROM tbl
```
---
First, you want to `TRIM` your data ... | Here's a more elegant / readable way:
```
SET @string = REPLACE(@string + '<END>', ',<END>', '')
```
---
if you can't be sure if last comma appear in string, use this:
```
SET @string = REPLACE(REPLACE(@string + '<END>', ',<END>', ''), '<END>', '')
``` | SQL : remove last comma in string | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I would like `Α` to display as A in the browser, but remain `Α` in my source code. My reason is that I would like to store the code in a SQL table as `Α`. However, anytime I add the literal `Α` and view the source code, I see A. Since this text might be resent back to the database (as input in a... | `Α` stays the same when viewing the source code in a separate browser window. I inserted `Α` into my own MySQL table called 'test' using the command below, and it remains the same.
```
INSERT INTO test (column1, column2) VALUES ('Α', ' ');
```
Perhaps you were using an element inspector to view... | You need to encode and decode your Html while storing to the database. Here is a Few links to help you.
<http://www.strictly-software.com/htmlencode>
<https://msdn.microsoft.com/en-us/library/windows/apps/hh464984.aspx> | vs Α displaying in browser and source | [
"",
"html",
"sql",
"ascii",
"coldfusion-10",
""
] |
```
create table test (id int, changed timestamp);
insert into test (id, changed) values (1, now());
insert into test (id, changed) values (2, now());
insert into test (id, changed) values (3, now());
select * from test;
+----+---------------------+
| id | changed |
+----+---------------------+
| 1 | 20... | It's because you used the `timestamp` data type for the 'changed' column, which updates every time the row is updated.
If you wanted this to work as expected I would change the 'changed' data type to `datetime` instead. | By default a `TIMESTAMP` column will be set to `CURRENT_TIMESTAMP` and this will also be used whenever you updating the row.
When you create you table using:
```
CREATE TABLE test (
id int,
changed TIMESTAMP
);
```
It will be the same as this:
```
CREATE TABLE test (
id int,
changed TIMESTAMP DEFAULT CURREN... | MySQL changes 'changed' column on update by itself | [
"",
"mysql",
"sql",
""
] |
Just curious... is there a command in TSQL which will delete rows I just selected from a table?
In pseudo SQL, something like
```
SELECT * FROM TableA THEN DELETE
```
Or
```
SELECT * FROM TableA WITH (DELETEROWS)
```
NOTE: I'm not just looking to delete rows, I want to return the rows to a temptable and *then* del... | You can get the rows that were *just* deleted using the [output clause](https://msdn.microsoft.com/en-us/library/ms177564.aspx):
```
DELETE FROM TableA
OUTPUT deleted.* --TODO name columns, identify table to insert into, etc
```
So, overall should be the same, just the order of operations is reversed. | You can use an `OUTPUT` statement in the `DELETE`. This will allow you to capture all the details of the deleted rows.
If you do the `SELECT` first, you would need to capture those rows into a table, and then delete the rows in the table.
If you repeat the logic for the `SELECT`, you *could* run into problems, becaus... | TSQL Select Delete | [
"",
"sql",
"sql-server",
"t-sql",
"sql-delete",
""
] |
I am trying to select from a transactions table using an IN clause determined by the value of a varchar parameter "@StatusCode". If @StatusCode is 'All Fail' then I want all records with status codes 1, 2, 3, or 5. Otherwise I want records with status code equal to the numeric value of @StatusCode. I have not found an ... | You can use a COALESCE trick if your incoming variable is null to match on all items -- like this
```
WHERE COALESCE(@nullinputvar,MatchingField) = MatchingField
```
but that does not work here because you only want to match on 4 items. I've modified this trick to work (by first creating a local variable that is nu... | try this query
```
SELECT * FROM Transactions
WHERE
(@StatusCode = 'All Failed' AND StatusCode IN (1,2,3,5))
OR
(IsNumeric(@StatusCode) = 1 AND StatusCode =(case when @StatusCode = 'All Failed' then StatusCode else convert(int, @StatusCode) end))
``` | SQL Server - Conditional IN clause | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I want to count the number of transactions for the first 30 days from an account's creation for all accounts. The issue is not all accounts were created at the same time.
```
Example: [Acct_createdTable]
Acct Created_date
909099 01/02/2015
878787 02/03/2003
676767 09/03/2013
```
I can't Declare a datetime varia... | I think what you're looking for is a basic `GROUP BY` query.
```
SELECT
ac.acctnumber,
COUNT(td.id)
FROM Acct_createdTable ac
LEFT JOIN transactiondate td ON
td.acct = ac.acctnumber
AND
td.transaction_date BETWEEN ac.create_date AND DATEADD(30, DAY, ac.create_date)
GROUP BY
ac.acctnumber
```
T... | An alternative solution would be to use `outer apply` like this:
```
select a.acct, o.First_30_days_count
from acct_createdtable a
outer apply (
select count(*) First_30_days_count
from transaction_table
where acctnumber = a.acct
and transactiondate between a.created_date and dateadd(day, 30, a.crea... | Count number of transactions for first 30 days of account creation for all accounts | [
"",
"sql",
"sql-server",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.