Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
```
select KeywordId,currentposition,PsnUpdateDate,PsnUpdateBy from seo.Tbl_KeywordPosition where psnupdatedate = '2015-01-22'
select KeywordId,currentposition,PsnUpdateDate,PsnUpdateBy from seo.Tbl_KeywordPosition where psnupdatedate = '2015-01-23'
1456 10 2015-01-22 00:00:00.000 Ananth
1467 8 2015-01-22... | you can use [UNION operator](http://www.techonthenet.com/sql/union.php)
```
SELECT KeywordId,currentposition,PsnUpdateDate,PsnUpdateBy
FROM seo.Tbl_KeywordPosition
WHERE psnupdatedate = '2015-01-22'
UNION
SELECT KeywordId,currentposition,PsnUpdateDate,PsnUpdateBy
FROM seo.Tbl_KeywordPosition
WHERE psnupdatedate ='2015... | The simplest way to merge these two statements is:
```
select old.KeywordId, oldposition, newposition, old.PsnUpdateBy
from
(select KeywordId,currentposition as oldposition, PsnUpdateBy
from seo.Tbl_KeywordPosition
where psnupdatedate = '2015-01-22' ) as old
inner join
(select KeywordId, currentposition a... | i want to merge two select statements | [
"",
"sql",
""
] |
I am unable to get clear cut answers on this contentious question .
[MSDN documentation](https://msdn.microsoft.com/en-us/library/ms190457.aspx) mentions
Clustered
* Clustered indexes **sort** and store the data rows in the table or view
based on their key values. These are the columns included in the
index defin... | Just to be clear. Presumably, you are talking about a simple query such as:
```
select *
from table t;
```
First, if all the data on the table fits on a single page and there are no other indexes on the table, it is hard for me to imagine a scenario where the result set is not ordered by the primary key. However, thi... | **Without ORDER BY, there is no default sort order even if you have clustered index**
in [**this link**](http://sqlblog.com/blogs/alexander_kuznetsov/archive/2009/05/20/without-order-by-there-is-no-default-sort-order.aspx) there is a good example :
```
CREATE SCHEMA Data AUTHORIZATION dbo
GO
CREATE TABLE Data.Numbe... | Do clustered index on a column GUARANTEES returning sorted rows according to that column | [
"",
"sql",
"sql-server",
""
] |
I have a requirement where there is a database column that stores DateTime such as 24-01-2015 22:31:49. Now, I can many such rows with different values in the column.
I need a query to update the column's data to 24-01-2015 00:00:00 for each row. (Basically convert datetime to date and save it in the same place).
I h... | The solution depends on the database. Here are exampels:
MySQL and DB2:
```
update t
set col = ate(col;
```
SQL Server 2008+:
```
update t
set col = cast(col as date);
```
Oracle:
```
update t
set col = trunc(col);
```
Postgres (and Postgres-derived databases):
```
update t
set col = date_trunc(... | ```
UPDATE table_name
SET date_time_col = CONCAT(date(date_time_col), ' 00:00:00')
```
Explanation: the **DATE** function will extract the date part of the datetime string. And the CONCAT function will add the 00:00:00 at the end of date. | Update database column data via sql query | [
"",
"sql",
""
] |
is it possible to create a query that join 2 table to calculate the total qty per stuff code ? I am using SQL Server 2008.
I have table Purchase
```
id_Purchase| stuff_code| qty
------------------------------
1 | G-001 | 6000
2 | G-002 | 4000
3 | G-003 | 2000
4 | G-001 ... | Below is one method, using common table expressions for purchases and sales summaries by stuff\_code.
```
CREATE TABLE dbo.Purchase(
id_Purchase int
CONSTRAINT PK_Purchase PRIMARY KEY
, stuff_code varchar(10)
, qty int
);
INSERT INTO dbo.Purchase VALUES
(1, 'G-001', 6000)
,(2, 'G-00... | You have data sets at two different granularities. Get them at the same grain and you can just do math straight across.
```
SELECT p.ID_Purchase
, p.stuff_code
, p.StuffPurchased
, ISNULL(s.StuffSold,0) as StuffSold
, p.StuffPurchased - ISNULL(s.StuffSold,0) as StuffLeft
FROM (SELECT
ID_Purchase
, stuff_code
, SUM(Qty... | what is the query to join 2 table to calculate qty per stuff | [
"",
"sql",
"sql-server",
"join",
""
] |
I'm looking to plot the number of views on an investment every week from creation date to current date.

Every time someone visits an investment, I'm inserting it to a table with
`investment_id`, `user_id` and `timestamp(datetime)`.
Table looks like ... | Needed is a temporary/virtual table like this:
```
+ ------------- + ---------- + ---------- + ---------- +
| investment_id | week_start | week_end | weeknumber |
+ ------------- + ---------- + ---------- + ---------- +
| 499 | 2015-01-02 | 2015-01-09 | 1 |
| 499 | 2015-01-09 | 2015-01-1... | something like this?
```
select week(time_stamp), count(investment_id)
group by time_stamp, investment_id
``` | Count of view week by week | [
"",
"mysql",
"sql",
""
] |
I am trying to select top 2 records from a database table result that looks like this
```
SubjectId | StudentId | Levelid | total
------------------------------------------
1 | 1 | 1 | 89
1 | 2 | 1 | 77
1 | 3 | 1 | 61
2 | 4 | 1 ... | You could use a correlated subquery:
```
select *
from ResultView rv1
where SubjectId || '-' || StudentId || '-' || LevelId in
(
select SubjectId || '-' || StudentId || '-' || LevelId
from ResultView rv2
where SubjectID = rv1.SubjectID
order by
total ... | I hope I'm understanding your question correctly. Let me know if this is correct:
I recreated your table:
```
CREATE TABLE stack (
SubjectId INTEGER(10),
StudentId INTEGER(10),
Levelid INTEGER(10),
total INTEGER(10)
)
;
```
Inserted values
```
INSERT INTO stack VALUES
(1,1,... | select top n record from each group sqlite | [
"",
"sql",
"sqlite",
"greatest-n-per-group",
""
] |
I have this query:
```
Select t1.col5,
t1.col6,
SUM(CASE WHEN t2.col1 = 'A' THEN t2.col2 ELSE 0
WHEN t2.col1 = 'B' THEN t2.col2 * -1 ELSE 0
END) AS price,
SUM(CASE WHEN t2.col1 = 'C' THEN t2.col2 + 100 ELSE 0
END) AS bonus
FROM t1, t2
WHERE t1.col1 = t2... | You can't use column aliases (or, for that matter, aggregates) in the `WHERE` clause. So what you want to do is use a subquery OR put the aggregates in a `HAVING` clause. I'll show the subquery below, which I think is easier since you don't have to reproduce all the keystrokes (you need to use the aggregates themselves... | Constraining on aggregate functions needs to be done in a `HAVING` clause:
```
Select t1.col5,
t1.col6,
SUM(CASE WHEN t2.col1 = 'A' THEN t2.col2 ELSE 0
WHEN t2.col1 = 'B' THEN t2.col2 * -1 ELSE 0
END) AS price,
SUM(CASE WHEN t2.col1 = 'C' THEN t2.col2 + 100 ELSE 0
EN... | Using the function SUM? | [
"",
"sql",
"sum",
""
] |
I have a table like this -
```
id cat_id
1 1,2
2 1,3
3 5,3,11
```
And I want to get count of those rows which have `cat_id = 1` (For Ex- in uppar case it count is 2). How can I do it ? | **To get count of `cat_id = 1`**
```
select count(*)
from (
select unnest(string_to_array(cat_id, ','))::int rowz
from foo ) t
where rowz = 1
```
**To get all `cat_id` and it's *total count***
```
select rowz cat_id,count(*) total_count from (
select unnest(string_to_array(cat_id, ','))::int rowz
... | You can use `LIKE`, for example :
```
SELECT COUNT(*)
FROM tbl
WHERE cat_id LIKE '1,%'
```
*if string is starting from something different ??? like 5* asked by @POHH :
```
SELECT COUNT(*)
FROM tbl
WHERE cat_id LIKE '%,1,%'
OR cat_id LIKE '1,%'
OR cat_id LIKE '%,1'
``` | How to get rows having specified value in sql? | [
"",
"sql",
"database",
"postgresql",
""
] |
I have a table 'order' containing summary order information and a table 'orderItem' with each item of the order.
My issue is: when selecting the Sum of column 'orderQTY' from the 'Order' table, I get an incorrect total if i join the orderItem table.
The first query below gives me the correct total.
However, as soon a... | It returns different results because the `join` multiplies the number of rows or filters out rows, both of which affect the sum. It is unclear what you really want to do. If you only want the sum of the quantities of orders that have orderlines, then use exists:
```
select sum(o.orderqty)
from [order] o
where exists... | You can sum once per grouping (in this case order.id) using the row\_number function:
```
select sum(orderqty)
from (
select
case row_number() over(partition by o.Id order by o.id)
when 1 then orderqty
else 0
end as orderqty
from [order] o
join OrderItem oi on ... | SQL SUM Query returns duplicate rows in result | [
"",
"sql",
"sql-server",
""
] |
Please tell me what I am missing in this example.
I have a stored procedure where I provide a default value of an empty string for a parameter. When I check the value, it comes back as `NULL`. I'm not sure if the default value is not being applied, or my `ISNULL` check is wrong.
Here is a simple example to illustrate... | Your if statement in effect says if it's empty string OR null, then treat is as empty string (print is null) - in your exec statements, you're in all cases passing in a null or an empty string, therefore hitting your isnull logic.
```
declare @string varchar(20)
set @string = ''
select isnull(@string, ''), -- '' woul... | Why not just use `IS NULL` if that is what you want?
```
CREATE PROCEDURE TestDefaultValueParam
@vcTestName varchar(100)= ''
AS
BEGIN
IF @vcTestName IS NULL
BEGIN
PRINT '@vcTestName IS NULL'
END
ELSE
BEGIN
PRINT '@vcTestName NOT NULL'
END
END;
```
Your logic is equivalent to:
... | Stored Procedure Default Value Not Being Set | [
"",
"sql",
"sql-server",
"stored-procedures",
""
] |
I'd like to select all the rows in the `plot` table where it exists in `watchlist`. For instance, with the example I've uploaded to [SQLFiddle](http://sqlfiddle.com/#!2/c54c01/7), I should be able to return rows `3`, `5` and `8` in `plot` with the query, because they exist in `watchlist`. The problem is, I am not sure ... | You can use `INNER JOIN` to check this:
```
SELECT t1.id
, t1.p_id
, t1.area
, t1.jobs
FROM plot t1
JOIN watchlist t2 ON t1.p_id = t2.p_id
```
[**SQLFiddle**](http://sqlfiddle.com/#!2/c54c01/15) | **Returns ROWS 3, 5, and 8**
```
SELECT *
FROM plot, watchlist
WHERE plot.p_id = watchlist.p_id;
``` | Select multiple values from one table based on values in another | [
"",
"mysql",
"sql",
"join",
""
] |
The following is a sample INSERT statement:
```
INSERT INTO
Foo (c1,c2)
VALUES
(a,1)
,(b,2)
,(c,3)
```
How do I insert these values to show the following result without redundant insert statements?:
```
c1 | c2
-------
a |1
a |1
a |1
a |1
a |1
a |1
b |2
b |2
b |2
b |2
b |2
b |2
c |3
c ... | You can use dynamic sql to replicate your insert x times:
```
declare @sql nvarchar(max)
select @sql = replicate('
INSERT INTO
Foo (c1,c2)
VALUES
(''a'',1)
,(''b'',2)
,(''c'',3)',6)
exec(@sql)
select * from Foo order by c1,c2
```
Alternatively, you can loop until you have the number of desired inse... | After inserting those values use `Recursive CTE` to do this
```
;with cte as
(
select c1,c2,1 as id from foo
union all
select c1,c2,id+1 from cte where id<5
)
Insert into Foo (c1,c2)
select c1,c2 from cte
```
Or do a `Cross Join` with `numbers` table. If you don't have `numbers` table use `master.dbo.spt_values` tabl... | Insert Duplicates Of Distinct Value In One SQL Statement | [
"",
"sql",
"sql-server",
"insert",
""
] |
## Situation
* I am new to the QuickBooks world.
* I have a `.qbw` file -> CompanyName.qbw
* It's a huge file that contain almost everything about my company.
* I want to query `some` data out of that file - NOT all , but some.:)
Let's say, I want to query only the `inventory report`.
* Within that inventory report,... | Not a direct answer, but some direction as you requested:
The QOBDC driver available here (<http://qodbc.com>) should allow you to access your qbw file like a SQL database and perform queries against it. There is a free trial, but it looks like you'll need to pay $150-$500 to buy this driver if you find that it works ... | Intuit (the people that make QuickBooks) offers something called the QuickBooks SDK specifically for situations like yours.
* <https://developer.intuit.com/docs/0250_qb>
It's free to download. Download, install, and you can connect to QuickBooks and extract any data you want or run any reports you want.
There's abou... | How to query some data out of a QuickBook(.qbw) file? | [
"",
"sql",
"quickbooks",
"quickbooks-online",
""
] |
I am have a table with data and now i need to return zero in select statement if there is no records in table for example. I need to use it in Stored Procedure.
```
-- If no records exists in below select statement
SELECT ID,Text,Date FROM tblData WHERE ID = 12
IF (@@ROWCOUNT = 0)
BEGIN
SELECT -5 AS ID
END
```
*... | ```
SELECT (CASE WHEN Ta.ID IS NULL THEN TBL.ID
ELSE Ta.ID END) AS ID,Ta.Text,Ta.Date
FROM (VALUES(-5)) AS TBL(ID)
LEFT JOIN
(
SELECT ID,Text,Date FROM tblData WHERE ID = 12
)
AS Ta ON Ta.ID = Ta.ID
``` | I always use an Exists statment.
```
if exists(SELECT ID FROM tblData WHERE ID = 12)
select 0 as RowsExist
else
select 1 as RowsExist
``` | Select statement to return constant when no records found in table in SQL Server 2008 | [
"",
"sql",
"sql-server",
"sql-server-2008",
"stored-procedures",
""
] |
I have a stored procedures that accepts a comma separated list, then makes copies of that list with quoted strings and brackets, then uses those in a dynamic sql statement to build a pivot table with flexible number of columns.
My problem is that sometimes my users submit a list with duplicates, and that makes the piv... | I guess we can add in distinct after you make the table, like this:
```
select @bracketed = @bracketed + quotename(rtrim(ltrim(Value))) + ', ',
@quoted = @quoted + quotename(rtrim(ltrim(Value)), '''') + ', '
from (
SELECT DISTINCT Value FROM [dbo].[fnSplitStringAsTable](@data, ',')
) T
```
If this fails try... | as an alternative solution you can dedupe in xml and convert back to varchar
```
Declare @data varchar(max) = '150593, 150593, 150603, 150578, 150604'
set @data= (select '''' + cast(cast('<d>'+replace(@data, ', ',',</d><d>')+'</d>' as xml).query('distinct-values(/d)') as varchar) +'''')
select @data
``` | SQL create distinct comma separated lists | [
"",
"sql",
"sql-server",
"csv",
"pivot",
""
] |
The date in my table looks like **2010-06-16 00:00:00.000**
When I use the below regular expression, no rows get selected.
```
select mydate from mytable where mydate like '2010%'
```
However, when I use this one, rows do get selected correctly.
```
select mydate from mytable where mydate like '%2010%'
```
So, I t... | If the `datatype` is `Datetime` you should use `Year()` function to filter the rows instead of `like`. You should not use `like` operator to filter the data from `Datetime` type.
If the `datatype` is `Datetime` then you won't be having `leading` or `trailing` spaces.
You do have appropriate `Date` functions in `Sql S... | You have to convert `datetime` that first in `varchar` to use `like`
```
select mydate from mytable
WHERE CONVERT(VARCHAR(10),mydate,120) like '2010%'
```
[DEMO](http://sqlfiddle.com/#!3/26ecfb/3) | regular expression not working on the datetime column | [
"",
"sql",
"sql-server",
""
] |
```
select round((cast(56/3 AS DECIMAL (4,2))),1)
```
is showing 18 output instead of 19 , where as actual value is 18.66.
My Round function is not working
please help. | The problem is `56/3` is an *integer* calculation which means no floating point numbers.
You need to use floating point numbers in the initial calculation e.g. `56.0/3`. Also, if you want to round to 19 then you need to round to the nearest *whole* number, `ROUND(x, 1)` will round to the first decimal place - you need... | Your section of the code:
```
CAST( 56/3 AS DECIMAL )
```
First evaluates the `56/3` which returns 18. This is then cast to decimal, giving 18.0.
You need to cast either the numerator or denominator before the division occurs.
The `round` function is working fine -- it's just not using the input you think it is. | sql server round | [
"",
"sql",
"asp.net",
"sql-server",
""
] |
In Oracle, if I make a composite index on 2 columns, then in which situation this index will be used to search the record ?
a) If my query has a WHERE clause which involves first column
e.g. WHERE first\_column = 'John'
b) If my query has a WHERE clause which involves second column
e.g. WHERE second\_column = 'Sharma... | **d) Both a or b**
If the leading column is used, Oracle will likely use a regular index range scan and just ignore the unused columns.
If a non-leading column is used, Oracle can use an [index skip scan](https://docs.oracle.com/database/121/TGSQL/tgsql_optop.htm#TGSQL238). In practice a skip scan is not used very of... | I happen to think that MySQL does a pretty good job of describing how composite indexes are used. The documentation is [here](http://dev.mysql.com/doc/refman/5.7/en/multiple-column-indexes.html).
The basic idea is that the index would normally be used in the following circumstances:
* When the `where` condition is an... | In Oracle, if I make a composite index on 2 columns, then in which situation this index will be used to search the record? | [
"",
"sql",
"oracle",
"indexing",
""
] |
I need to make row numbering with ordering, partitioning and grouping. Ordering by `IdDocument, DateChange`, partitioning by `IdDocument` and grouping by `IdRole`. The problem is in grouping especially. As it could be seen from the example (`NumberingExpected`) `DENSE_RANK()` must be the best function for this purpose ... | Since 2012 you could use `LAG`/`LEAD`, but in 2008 it is not available, so we'll emulate it. Performance could be poor, you should check with your actual data.
This is the final query:
```
WITH
CTE_rn
AS
(
SELECT
Main.IdRole
,Main.IdDocument
,Main.DateChange
,ROW_NUMBER() OVER(PART... | This might not be pretty but it does create the required output.
```
; with cte as (
select l.Id,l.IdRole,l.IdDocument,l.NumberingExpected,l.DateChange,
(select min(x.DateChange) from @LogTest x where x.IdDocument = l.IdDocument and x.IdRole = l.IdRole and x.id<=l.id and
x.id > (select max(y.id) from ... | How to make row numbering with ordering, partitioning and grouping | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I need to select the employees that registered in the company this year; the field is a date type(field name :datemp) so i used :
```
SELECT employee_name
FROM employees
WHERE datemp BETWEEN to_date(01-JAN-2015) AND to_date (31-DEC-2015)
```
is there another method i can say that the year of a field that has a date... | You can pull it from `sysdate`
```
SELECT employee_name
FROM employees
WHERE EXTRACT(year FROM datemp) = EXTRACT(year FROM sysdate)
``` | You can always do:
```
select employee_name
from emploees
where trunc(datemp, 'yyyy') = to_date('01/01/2015', 'dd/mm/yyyy'); -- or trunc(sysdate, 'yyyy') if you need it to refer to this year
```
(or even ... `to_char(datemp, 'yyyy') = '2015';`)
Bear in mind that if you do use a function on the datemp column, any ... | How to select actual year in Oracle Date? | [
"",
"sql",
"oracle",
"oracle10g",
"oracle-sqldeveloper",
""
] |
I have the following query:
```
select * from [lead].[ContactFeedback] cf
where cf.LeadId in
(select LeadId from [lead].[LeadDetails]
where TeleportReference in (122096,
122097,
122098))
order by LeadId Desc
```
The results are something like this :
```
FeedbackDate LeadId
2015-01-23 16:25:13.5... | ```
select LeadId, Max(FeedbackDate)
from [lead].[ContactFeedback] cf
where cf.LeadId in
(select LeadId from [lead].[LeadDetails]
where TeleportReference in (122096, 122097, 122098))
group by LeadId
order by LeadId Desc
``` | Use `Window Function`
```
select leadid,feedbackdate from (
select row_number() over(partition by leadid order by feedbackdate desc) rn,*
from yourtable) a
where rn=1
``` | SQL - Select Top 1 multiple lines of the same id | [
"",
"sql",
"sql-server",
""
] |
I have written a stored procedure for inserting data into my table. These are my table's columns with their datatype:
```
Ad nvarchar(150),
Yazar nvarchar(150),
SayfaSayisi smallint,
KategoriId int
Gmc datetime,
HostName nvarchar(150)
```
The problem is that `Gmc` and `HostName` have their own default values. So I c... | You need remove `ID` from insert list
```
Insert into Kitap(Ad,Yazar,SayfaSayisi,KategoriId)
values(@Ad,@Yazar,@SayfaSayisi,@KategoriId)
```
or add a value for it as below
```
Insert into Kitap(Id,Ad,Yazar,SayfaSayisi,KategoriId)
values(@ID, @Ad,@Yazar,@SayfaSayisi,@KategoriId)
``` | Instead of :
```
Insert into Kitap(Id,Ad,Yazar,SayfaSayisi,KategoriId)
values(@Ad,@Yazar,@SayfaSayisi,@KategoriId)
```
Use:
```
INSERT INTO Kitap(Ad,Yazar,SayfaSayisi,KategoriId)
VALUES (@Ad,@Yazar,@SayfaSayisi,@KategoriId)
```
You are asking SQL engine that you will provide id (an additional field) as well (field... | Confusion about Stored Procedure | [
"",
"sql",
"stored-procedures",
""
] |
Does "group by" clause automatically guarantee that the results will be ordered by that key? In other words, is it enough to write:
```
select *
from table
group by a, b, c
```
or does one have to write
```
select *
from table
group by a, b, c
order by a, b, c
```
I know e.g. in MySQL I don't have to, but I would... | `group by` does not order the data neccessarily. A DB is designed to grab the data as fast as possible and only sort if necessary.
So add the `order by` if you need a guaranteed order. | > An efficient implementation of group by would perform the group-ing by sorting the data internally. That's why some RDBMS return sorted output when group-ing. Yet, the SQL specs don't mandate that behavior, so unless explicitly documented by the RDBMS vendor I wouldn't bet on it to work (tomorrow). OTOH, if the RDBMS... | Does "group by" automatically guarantee "order by"? | [
"",
"sql",
"database",
"group-by",
"database-agnostic",
""
] |
This one is not easy at all it seems.
I have a table **data**:
```
String ticker, Double price, Date time
--------------------------------------
```
How can I given the above table:
**SELECT ticker WHERE price has increased x percent AND time BETWEEN '2014-10-01' AND '2014-10-31'** ?
What one needs to do is for ea... | In postgresql, we can efficiently perform a computational query as this:
Note, we are first selecting all the tickers from another table Ticker first, but this could be DISTINCT(ticker) on the data table as well.
```
SELECT A.name, A.symbol, B.price AS start, C.price AS last, D.percent from ticker A,
lateral ( SELEC... | Probably overkill using a cross join but I though you might be after any time in the range where a price compared to a future price for same ticker was greater than 5%
```
SELECT DS.Ticker, ds.Time as StartTime, ds.Price StartPrice,
De.Time as EndTime, De.Price as endPrice,
De.pri... | Selecting all tickers where price has increased by 5 percent within a time range | [
"",
"sql",
"database",
""
] |
I have a PostgreSQL database table called "user\_links" which currently allows the following duplicate fields:
```
year, user_id, sid, cid
```
The unique constraint is currently the first field called "id", however I am now looking to add a constraint to make sure the `year`, `user_id`, `sid` and `cid` are all unique... | The basic idea will be using a nested query with count aggregation:
```
select * from yourTable ou
where (select count(*) from yourTable inr
where inr.sid = ou.sid) > 1
```
You can adjust the where clause in the inner query to narrow the search.
---
There is another good solution for that mentioned in the comments,... | From "[Find duplicate rows with PostgreSQL](https://stackoverflow.com/questions/14471179/find-duplicate-rows-with-postgresql/14471928#14471928)" here's smart solution:
```
select * from (
SELECT id,
ROW_NUMBER() OVER(PARTITION BY column1, column2 ORDER BY id asc) AS Row
FROM tbl
) dups
where
dups.Row > 1
``` | How to find duplicate records in PostgreSQL | [
"",
"sql",
"postgresql",
"duplicates",
""
] |
I have the following query I'd like to run on my database:
```
SELECT
u.UserId, u.FullName, u.Location, csr.SponsorId
FROM
[User] u
LEFT JOIN
(SELECT
csr.SponsorId
FROM
ClubSponsorRelation csr
WHERE
csr.ClubId = @clubId) AS csr ON u.UserId = csr.SponsorId
WHERE ... | Give this a try. Use `Not Exists` to find the users, since you want to find users who is not present in `ClubSponsorRelation` selecting `csr.SponsorId` doesn't make any sense to me.
```
SELECT u.UserId,
u.FullName,
u.Location
FROM [User] U
WHERE NOT EXISTS (SELECT 1
FROM ClubSpons... | This is up to the execution engine. The easiest way to check is to let the server generate an execution plan for you - for example, in Management Studio, check `Include actual execution plan`. That will give you a good idea of how the query is actually going to be run, and why.
Note that the reasoning is quite complex... | How does SQL Server handle the following query? | [
"",
"sql",
"sql-server",
""
] |
Hello I'm trying to know how to exclude columns from SELECT statement ,
I have 2 tables joined.
First Table:
```
|--ID--|--Name--|--Date 1--|--Date 2--|
```
Second Table:
```
|--ID--|--Tax--|--Total--|
```
Output:
```
|--ID--|--Name--|--Date 1--|--Date 2--|--ID--|--Tax--|--Total--|
```
This is the output what... | You can make your select statement more specific and get rid of the wildcard(s) \*
```
SELECT firstTable.Name, SecondTable.Tax, SecondTable.Total
...
```
Take a look at [w3schools SQL SELECT Statement](http://www.w3schools.com/sql/sql_select.asp) for more information about the SELECT statement. | Just enumerate the fields you want to show, instead of putting \*, which means "all fields":
```
Dim loadq As String =
"SELECT HelperEmpEarns.[Name], HelperEmpDed.Tax, HelperEmpDed.Total" & _
"FROM (HelperEmpEarns RIGHT JOIN HelperEmpDed ON HelperEmpEarns.EmpPID = HelperEmpDed.EmpPID) "... | Excluding Columns From SELECT Statement | [
"",
"sql",
"vb.net",
"ms-access-2007",
""
] |
I have a data something like below.
```
ID | Value
------------
1 | A
1 | B
1 | C
2 | A
2 | C
3 | C
```
I'm trying to get ID which has A but not including B.
In this case, I should only get ID 2 as a result.
If I query like
```
SELECT DISTINCT ID
FROM TABLE
WHERE (VALUE = 'A' AND VALUE <> 'B')
```... | You need to exclude any ID's that contain the value 'B'. you can do this with a left join and a check for null... i.e. no match.
```
select d.*
from data d
left join (select id from data where value = 'B') x --exclude these
on d.id = x.id
where x.id is null
and d.value = 'A'
``` | Even though you accepted an answer, I'll write another variant. I think it is easier to write and understand. In terms of performance you have to check how different variants work on your system with your real data.
```
DECLARE @T TABLE (ID int, Value char(1));
INSERT INTO @T (ID, Value) VALUES (1, 'A');
INSERT INTO ... | T-SQL Query - How to not include some results from different row | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am new to the `RANK` and `CTE` queries. The following is my query:
```
SELECT
*
,ROW_NUMBER() OVER(PARTITION BY name, Product ORDER BY Date desc) AS 'RANK'
FROM
Config
WHERE
Name
IN
(SELECT
name
FROM
Config
GROUP BY
Name
,Product
,Amount... | From the looks of it, you want to delete duplicate entries for `Name` and `Product` leaving the newest one. You can simplify your query with this:
```
SELECT
*,
RN = ROW_NUMBER() OVER(PARTITION BY Name, Product ORDER BY [Date] DESC)
FROM Config
```
You can then put it in a CTE and execute the `DELETE`.
```
C... | You can use a CTE:
```
with todelete as (<your query here>)
delete from todelete
where [rank] = 1;
``` | DELETE FROM Table WHERE 'RANK' > 1 | [
"",
"sql",
"sql-server",
"conditional-statements",
"rank",
"sql-delete",
""
] |
Greeting,
My question; Whether or no sql query (SELECT) **continues or stops reading data (records) from table when find the value** that I was looking for?
referance: "In order to return data for this query, mysql must start at the beginning of the disk data file, read in enough of the record to know where the catego... | Yes it scans the entire file. Unless you put something like
```
select * from user where id=100 limit 1
```
This of course will still search entire rows if id 100 is the last record.
If id is a primary key it will automatically be indexed and searching would be optimized | The RDBMS **reading data from disk** is something you cannot know, you should not care and you must not rely on.
The issue is too broad to get a precise answer. The engine reads data from storage in blocks, a block can contain records that are not needed by the query at hand. If all the columns needed by the query is ... | Whether or not SQL query (SELECT) continues or stops reading data from table when find the value | [
"",
"mysql",
"sql",
""
] |
I have a PostgreSQL table
```
CREATE TABLE my_table
(
id serial NOT NULL,
name text,
actual boolean DEFAULT false,
CONSTRAINT my_table_pkey PRIMARY KEY (id),
);
```
How can I set a constraint that only one row can have `actual` flag set to `TRUE`? | You can create a unique [partial index](https://www.postgresql.org/docs/current/indexes-partial.html) on that column only for true values:
```
create unique index on my_table (actual)
where actual = true;
```
SQLFiddle: <http://sqlfiddle.com/#!15/91f62/1> | My approach would add another feature to an index-based only solution: automatic deactivation of the current flag when setting the flag on another row.
That would involve, of course a trigger.
I would also recommand, as suggested by Frank Heikens, storing "not actual" state as a `null` instead of `false`. In postgres... | PostgreSQL constraint - only one row can have flag set | [
"",
"sql",
"postgresql",
""
] |
I am having trouble understanding this code. It actually seems to work, but I don't understand how the correct value for activity year and month is "found" get the proper min and max? Or is it running all permutations getting the highest? This is very strange to me.
I do understand how the dateadd works, just not how ... | for both the `min` and `max` function call, the algorithm is
```
dateadd(mm, (ActivityYear - 1900) * 12 + ActivityMonth - 1 , 0)
```
Your query compute all possible date from the `Compensation` table using this algorithm. Then, you select the minimum date as `StartDate` and the maximum as `EndDate`.
This is how the ... | It is converting the columns `ActivityYear` and `ActivityMmonth` to a date. It is doing so by counting the number of months since 1900 and adding them to time zero. So, Jan 2000 would become something like Jan, 100. This seems like a very arcane calculation, because dates that are about 2,000 years old are not really u... | How does this aggregated query find the correct values | [
"",
"sql",
"sql-server",
""
] |
I have a table where I store items and the time where they are relevant. For this question the following columns are relevant:
```
CREATE TABLE my_items
(
id INTEGER,
category INTEGER,
t DOUBLE
);
```
I want to select all items from a specific category (e.g. 1) and the sets of items that have a time wit... | You can use a join. Take your subquery that selects all category 1 items, and join it with the original table on the condition that the time is within +/- five. It's possible that duplicate rows are returned, so you can group by id to avoid that:
```
SELECT t.*
FROM myTable t
JOIN (SELECT id, timeCol FROM myTable WHER... | You can use a single query with all you criteria if there is only one table
`SELECT id,t from my_items where category=1 AND t >= t_q1-5 AND t <= t_q1+5;`
If there is two tables, use a right join on the timestamps table for performance. | Finding item and dependent set of items from the same mysql table in one query | [
"",
"mysql",
"sql",
""
] |
I am trying to sum the value by date, here is the query i currently have,
```
SELECT SUM(LineTotalValue) AS Value, DateTimeCreated
FROM SOPOrderReturnLine AS SOPOrderReturnLine
WHERE (AnalysisCode1 LIKE 'value%')
GROUP BY DateTimeCreated
ORDER BY DateTimeCreated desc
```
Here is the what what data lo... | ```
SELECT SUM(LineTotalValue) AS Value,
CONVERT(date, DateTimeCreated)
FROM SOPOrderReturnLine AS SOPOrderReturnLine
WHERE AnalysisCode1 LIKE 'value%'
GROUP BY CONVERT(date, DateTimeCreated)
ORDER BY CONVERT(date, DateTimeCreated) desc
``` | You can try this
```
SELECT SUM(LineTotalValue) AS Value,
CAST(DateTimeCreated AS DATE)
FROM SOPOrderReturnLine AS SOPOrderReturnLine
WHERE AnalysisCode1 LIKE 'value%'
GROUP BY CAST(DateTimeCreated AS DATE)
ORDER BY CAST(DateTimeCreated AS DATE) desc
``` | SQL server, Order by datetime value | [
"",
"sql",
"sql-server",
""
] |
I have some problems with the order of my select and don't know how to fix it.
The hierarchy should look like this:
```
10
100
1001
1003
1004
1007
10010
20
210
2101
220
22100
22101
```
But when I do a usual order by this hierarchy I get it like that:
```
10
20
100
210
220
1001
...
```
Does anyone have an idea how ... | Your column is of a number data type. Convert it to a string like this
```
select * from your_table
order by cast(your_column as varchar(20))
``` | OK, got it
```
SELECT *
FROM Table
ORDER BY RIGHT('00000000' + CAST(ID AS VARCHAR),8)
``` | T SQL - Special order for hierarchy | [
"",
"sql",
"sql-server",
""
] |
All i'm trying to do is count how many bookings have requested wheelchair access not sure with the best way....
```
using (var context = new TalyllynContext())
{
var count = context.Bookings.SqlQuery(" SELECT * FROM dbo.Booking Where Wheelchair_Access = 'true' ").Count();
}
ViewBag... | ```
using (var context = new TalyllynContext())
{
ViewBag.Count = context.Bookings.SqlQuery(" SELECT * FROM dbo.Booking Where Wheelchair_Access = 'true' ").Count();
}
return View()
``` | If you are using razor do something like this.
```
<p>@ViewBag.Count</p>
```
That will display the value in the view if you use the code you showed. | Count rows of data and display in view ASP.net MVC | [
"",
"sql",
"asp.net",
"asp.net-mvc",
"count",
"data-retrieval",
""
] |
So I'm a bit confused as to why I am receiving this error. Here's my (very simple) query.
```
SELECT * FROM consumer_info, respite INNER JOIN respite ON consumer_info.consumer_id = respite.consumer_id;
```
I've even rewritten it and aliased both fields (`consumer_info.consumer_id` and `respite.consumer_id`) to no ava... | You're selecting from a table you're also joining:
```
SELECT *
FROM consumer_info, respite
^^^^^
INNER JOIN respite ...
^^^
```
You can join/use a table multiple times, but each usage of the table MUST have its own unique alias. Try
```
FROM consumer_info, respite
INNER JOIN respite... | You are mixing up two join syntaxes - the pre-ANSI and ANSI joins. You should rewrite the statement as follows:
```
SELECT *
FROM consumer_info
INNER JOIN respite ON consumer_info.consumer_id = respite.consumer_id;
```
In pre-ANSI syntax the join would look like this (**not recommended**):
```
SELECT *
FROM consumer... | Not unique/table alias 'respite' | [
"",
"mysql",
"sql",
""
] |
I would like to be about to round SQL Time to the nearest hour if the time value is 1min away from the nearest hour. (Time is in 24 hour clock format)
For instance
```
23:59 - > 00:00
11:30 - > 11:30
03:59 - > 04:00
01:15 - > 01:15
12:59 - > 13:00
```
This is what I was able to do so far, but it is only rounding to ... | You can make a decision if you try to add one minute and then test the result:
```
SELECT
cast(dateadd(millisecond, 29999, @t) as smalldatetime) as T1,
cast(dateadd(millisecond, 29999, @t2) as smalldatetime) as T2
,CASE WHEN SUBSTRING(CAST(DATEADD(MINUTE, 1, @t) as nvarchar(15)),4,2) = '00' THEN DATEADD(... | This seems like a strange requirement -- just getting rid of one particular minute out of 60. But a `case` statement should do what you want:
```
select (case when datepart(hour, time) = 59
then dateadd(hour, datediff(hour, 0, @t) + 1, 0)
else @t
end)
``` | Round SQL Time to nearest hour if 1min away from nearest hour | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
Sorry if the question is dumb. But I have a real problem in doing this in a right way.
I have 1st table, which are `announcements` , where I have `Title, Description` where users add some announcements.
There is another table, where we have
1 `id, email, keyword1,keyword2,keyword4,keyword5` where users add up to 5 k... | Do it in an opposite way. Do not match keywords against your announcements, but match announcements against your table with users+keywords.
When you add a new announcement, build a special string with your new query, which will directly match keywords in `users` table. For example, lets assume that your added announce... | It makes it a little more difficult because the keywords are arrayed on the table. I would recommend considering having those on another table and I believe it will help you with the query.
I think something like this will work out
```
select * from users u
inner join announcement a on instr(a.description, u.keyword1... | mysql query strategy to find keyword matches | [
"",
"mysql",
"sql",
""
] |
I can't seem to figure out how to use the opposite of isnull or ifnull statements in sql. I need to say if `a.Error1` is not null -- then print the `' - '` and the + `CHAR(13)+CHAR(10)`. Basically There should be no dash or no new line break if the a.Error1 comes back null. So print the information if the field isn't n... | You can use `CASE`:
```
SELECT a. ....
(CASE WHEN a.Error1 IS NOT NULL
THEN ' - ' + a.Error1 + CHAR(13)+CHAR(10)
ELSE ''
END) +
(CASE WHEN a.Error2 IS NOT NULL
THEN ' - ' + a.Error2 + CHAR(13)+CHAR(10)
ELSE ''
END) +
(CASE W... | Yes! i know i'm like 5 years too late but i too enountered this problem.
It's weird how it doesn't exist some kind of !ISNULL() but whatever.
Try this for a cleaner code:
```
select a. ....
IIF(a.Error1 IS NOT NULL, ' - ' + a.Error1 + CHAR(13)+CHAR(10) , '') as Error1,
IIF(a.Error1 IS NOT NULL, ' - ' + a.Error1 +... | using sql - Is not null in a select statement | [
"",
"sql",
"sql-server",
"null",
"isnull",
"ifnull",
""
] |
In sql server, From my desktop I connected to the server. And I want to move a data from a database to another. I have used both select into and import wizard. But import wizard seems to be slow. Why?
Is there any methodology changes for transferring data ? | Select into is a SQL query, and it is executed directly.
Import and Export Wizard is a tool which invokes Integration Services (SSIS).
Wizard is slow, but can use various data sources
More about export/import wizard
<https://msdn.microsoft.com/en-US/en-en/library/ms141209.aspx>
Topic about select into and expo... | I agree with Andrey. The Wizard is super slow. If you perform a Google search on "sql server import and export wizard slow", you will receive nearly 50k hits. You may want to consider a couple of other options.
**BCP Utility**
Note: I have used this on a number occasions. Very fast processing.
The bcp utility bulk c... | Select into VS Import and export wizard in sql server | [
"",
"sql",
"import",
"select-into",
"sql-import-wizard",
""
] |
I have three tables, persons, email, and personemail. Personemail basically has a foreign key to person and email so one person can be linked to multiple email addresses. Also the email table has a field named primaryemail. This field is either 1 or 0. The primary email flag is used for pulling emails into reports/invo... | Creating temporary tables is a very expensive way to do this, and using loops is a bad idea is SQL, as they are slow, since they can't be optimized. The typical method uses subqueries instead. To start, try doing this:
```
CREATE TABLE #TEMP(PERSONID INT, PRIMARYEMAIL INT,FLAG INT)
CREATE INDEX IDX_TEMP_PERSONID ON #T... | Single query to set primaryEmail=1 for first email for each person except ones who already have primary email:
```
UPDATE Account.tbEmail E SET E.primaryEmail=1
WHERE
E.EmailID in (
-- get min email id for each person
SELECT min(PE.EmailID) FROM Account.tbPersonEmail PE
-- but exclude per... | Need a less expensive query | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have been trying to find a way to select/delete the duplicated payroll records from my dataset below.
```
ID HDate SiteID RecordID EmployeeID TimeWorked
8066839 24/01/2015 164 840 28930 240
7982224 08/11/2014 164 840 28812 390
8066838 23/01/2015 164... | I think you were very close to solving this yourself:
```
SELECT *
FROM StaffHours
WHERE (SiteID = '164') AND (ID IN
(SELECT Min(ID)
FROM StaffHours
WHERE (SiteID = '164')
GROUP BY RecordID
... | If `ID` is a key or unique:
```
DELETE FROM StaffHours
WHERE ID =
(SELECT MIN(ID) FROM StaffHours
WHERE SiteID = 164
AND (SELECT count(*) FROM StaffHours sh WHERE sh.RecordID = RecordID AND SiteID = sh.SiteID) > 1
GROUP BY RecordID)
``` | SQL Server Duplicate Payroll Records | [
"",
"sql",
"sql-server-2008",
"duplicates",
""
] |
I'm currently working on a query that returns records from within a date range. The ideal is for the start date to be everything from 2015 onward. In theory, shouldn't each of the three SET statements below set the variable to 2015\*?
```
DECLARE @startDate datetime;
SET @startDate = '20150101';
SET @startDate = YEAR(... | The answer to your question is "No". The variable `@StartDate` is date time. This doesn't make sense:
```
set @startDate = 2015
```
It doesn't make sense. An integer that looks like a year is not a date.
If you want the first day of the year, you can do:
```
set @startDate = dateadd(day,
1 ... | I think this would work (for SQL-Server):
```
SET @startDate = cast(YEAR(GETDATE()) as varchar(4))
SET @startDate = cast(DATEPART(yyyy,GETDATE()) as varchar(4))
```
This will show you what's happening:
```
DECLARE @startDate datetime
SET @startDate = '20150101'
select @startdate
SET @startDate = YEAR(GETDATE())
sel... | SQL YEAR(GETDATE()) | [
"",
"sql",
"sql-server",
"t-sql",
"variables",
""
] |
I have a query like
```
SELECT
`campaign_question_options`.`text`,
COUNT(`campaign_submission_answers`.`answer`) as `count`
FROM `campaign_questions`
INNER JOIN `campaign_question_options` ON `campaign_question_options`.`campaign_question_id` = `campaign_questions`.`id`
LEFT JOIN `campaign_submis... | Update on this question, I tried attempting this query from a different angle. It seems to output the results I expect, however I am not sure if it's the most efficient way since I have had to use a subquery.
```
SELECT `campaign_question_options`.`text`, COUNT(`csa`.`answer`) FROM `campaign_questions`
INNER JOIN `cam... | When you have `left join`s and you want to filter on an any table but the first, you need to put the conditions in the `on` clause:
```
SELECT cqo.`text`,
COUNT(csa.`answer`) as `count`
FROM `campaign_questions` cq INNER JOIN
`campaign_question_options` cqo
ON cqo.`campaign_question_id` = cq.`id` LE... | Grouping results with left and inner join with zero counts | [
"",
"mysql",
"sql",
"join",
"count",
"group-by",
""
] |
First and Foremost, this is part of an assignment.
I am trying to use the COUNT function as part of a query in relation to the Northwind database. The query should return the CustomerID, CompanyName, and **the number of of orders placed for each respective customer**.
Of course the first two parts are easy, but I can... | You need a `group by` clause, which will allow you to split your result in to groups, and perform the aggregate function (`count`, in this case), per group:
```
SELECT Customers.CustomerID, Customers.CompanyName, COUNT(*)
FROM Orders, Customers
WHERE Customers.CustomerID = Orders.CustomerID;
GROUP BY Customer... | The below query should work.
```
SELECT Customers.CustomerID, Customers.CompanyName, COUNT(*)
FROM Orders, Customers
WHERE Customers.CustomerID = Orders.CustomerID group by Orders.CustomerID
``` | Using the COUNT function in SQL | [
"",
"sql",
"select",
"count",
""
] |
Here's my function which is supposed to return the top row of the record:
```
ALTER FUNCTION [dbo].[fn_PAT_LastTS]
(
-- Add the parameters for the function here
@PATcode varchar(50)
)
RETURNS datetime
AS
BEGIN
-- Declare the return variable here
DECLARE @lastTS datetime
-- Add the T-SQL statement... | Try this:
```
SELECT TOP 1 @lastTS = tsdate FROM timesheet WHERE pat = @PATcode ORDER BY tsdate DESC
```
# EDIT:
The problem is with how you're calling the function:
```
SELECT dbo.fn_PAT_LastTS('ZZ793843') FROM timesheet
```
This will select all rows from `timesheet` with one column whose value is the result of `... | The scalar is being called for each row in timesheet.
Try the following:
```
select dbo.fn_PAT_LastTS('ZZ793843')
``` | Unable to return top record in a T-SQL scalar function | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I am trying to get the `MAX()` of a column and use that value to perform a `DATEADD()` operation,
```
CONVERT(Datetime, DATEADD(MONTH, tb_files.file_retentiondate, MAX((SELECT tb_records.rec_record_date FROM tb_records)))) AS ExpiryDate
```
What I tried is this:
```
SELECT tb_files.file_pk AS 'File Number',
t... | You can't wrap a subquery with a MAX() function like that... Try this:
```
SELECT tb_files.file_pk AS 'File Number',
tb_files.file_subject AS 'File Subject',
CONVERT(Datetime, DATEADD(MONTH, tb_files.file_retentiondate, (SELECT MAX(tb_records.rec_record_date) FROM tb_records))) AS ExpiryDate,
tb_c... | The error message is pretty descriptive. SQL does not allow you to use a subquery for an argument to an aggregation function. The simple solution is to move the aggregation inside the subquery:
```
. . .
CONVERT(Datetime, DATEADD(MONTH, tb_files.file_retentiondate,
(SELECT MAX(tb_records.rec_record_da... | Nested SELECT statement in DateAdd() | [
"",
"sql",
"sql-server",
"t-sql",
"select",
"nested",
""
] |
I have data for current year as well as next year in a table.
Sample Table data:
```
Year,Period,prd_Desc,Amount
2014,11, Humira, 120
2015,11, humira, 140
```
Key Coulmn are Year,Period,prd\_Desc
If the data present for next year and for same period, i need that value in a separate column. Like below
```
Y... | Assuming your real table has some more rows (i.e. more years and more periods) than you show us, this would be a more generic solution:
```
WITH t AS
(SELECT YEAR,Period,prd_Desc,Amount,
LEAD(amount, 1) OVER (PARTITION BY prd_Desc, period ORDER BY YEAR) AS amount_next_year
FROM a_table)
SELECT *
F... | You can achieve this with a subquery.
```
select t.*, (select amount from sampleTableData where year = t.year+1 and period = t.period and prd_desc = t.prd_desc) Amount_next_yr from sampleTableData t
``` | Getting a specific row value in a column | [
"",
"sql",
"oracle",
"informatica",
""
] |
Right now I just have
```
INSERT INTO MY_TABLE (VAL1, VAL2)
SELECT VAL1, VAL2 FROM OTHER_TABLE;
```
However, if `MY_TABLE` already has the values `(1, 2)`, I don't want to let it insert `(2,1)` if `(2,1)` is in `OTHER_TABLE`;
Is there a way to do this here, or even while creating the tables?
I have tried to `ALTER`... | Try this.
```
SELECT VAL1,
VAL2
FROM OTHER_TABLE a
WHERE NOT EXISTS (SELECT 1
FROM my_table b
WHERE ( a.val1 = b.val2
AND a.val2 = b.val1 )
OR ( a.val1 = b.val1
AND a.val2 = b.val2 ... | We can place a condition while creating the table itself:
create table my\_table
(
val1 int,
val2 int,
check( val,val2 not in (select val1,val2 from other\_table,my\_table where my\_table.val1=other\_table.val2 and my\_table.val2=other\_table.val1)
union
select val1,val2 from my\_table mt1,mt2 where mt1.val1=... | Don't insert any combination of duplicates in SQL | [
"",
"mysql",
"sql",
""
] |
How to find the last day os the month in postgres?
I have a date columns stored as numeric(18) in the format(YYYYMMDD)
I am trying it to make it date using
```
to_date("act_dt",'YYYYMMDD') AS "act date"
```
then find the last day of this date:
like this:
```
(select (date_trunc('MONTH',to_date("act_dt",'YYYYMMDD')) ... | If you're using Amazon AWS Redshift then you can use Redshift's `LAST_DAY` function. While Redshift is based on PostgreSQL, **the `LAST_DAY` function is not available in PostgreSQL**, for a solution for PostgreSQL [see @wspurgin's answer](https://stackoverflow.com/a/45740174/159145).
<https://docs.aws.amazon.com/redsh... | For anybody coming to this question looking for the *Postgres* way to do this (not using Redshift), here's how you'd do it:
```
SELECT (date_trunc('month', '2017-01-05'::date) + interval '1 month' - interval '1 day')::date
AS end_of_month;
```
Replacing the `'2017-01-05'` with whatever date you want to use. You can m... | How to get the last day of month in postgres? | [
"",
"sql",
"amazon-redshift",
""
] |
Current SQL:
```
select t1.*
from table t1
where t1.id in ('2', '3', '4')
```
Current results:
```
id | seq
---+----
3 | 5
2 | 7
2 | 5
3 | 7
4 | 3
```
Attempt to select maxes:
```
select t1.*
from table t1
where t1.id in ('2', '3', '4')
and t1.seq = (select max(t2.seq)
fr... | Group By is your friend:
```
SELECT
id,
MAX(seq) seq
FROM TABLE
GROUP BY id
```
EDIT: Response to comment. To get the rest of the data from the table matching the max seq and id just join back to the table:
```
SELECT t1.*
FROM TABLE t1
INNER JOIN (
SELECT
id
MAX(seq) as seq
FROM TA... | This SQL Query will give you max seq from individaul ID.
```
SELECT t1.*
FROM t1
WHERE t1.id in ('2', '3', '4')
AND NOT EXISTS (
SELECT *
FROM t1 t2
WHERE t2.id = t1.id
AND t2.seq > t1.seq
``` | Max rows by group | [
"",
"sql",
"oracle",
""
] |
I have column (Numbers) which has values as follows:
```
1,2,3
1,2,3,
1,2,3,,,
1,2,3,,,,,,
```
I want to Trim all the Commas at the end of string, So that result would be
```
1,2,3
1,2,3
1,2,3
1,2,3
```
I have tried below Query but by this we can remove only one last comma
```
DECLARE @String as VARCHAR(50)
SET @S... | You can do this using:
```
LEFT(Numbers, LEN(Numbers) - (PATINDEX('%[^,]%', REVERSE(Numbers)) - 1))
```
The premise of this is you first reverse the string using [`REVERSE`](https://msdn.microsoft.com/en-us/library/ms180040.aspx):
```
REVERSE(Numbers) --> ,,,,,,3,2,1
```
You then find the position of the first char... | Because there are multiple occurrences you can't do it with a simple builtin function expression, but a simple user defined function can do the job.
```
create function dbo.MyTrim(@text varchar(max)) returns varchar(max)
as
-- function to remove all commas from the right end of the input.
begin
while (right(@text... | TrimEnd Equivalent in SQL Server | [
"",
"sql",
"sql-server-2008",
"trim",
""
] |
I've been looking around for the answer but I didn't find anything. Sorry if the answer has been given elsewhere.
Here is my problem :
I have a calculated member which is the number of items (of the current member) divided by the total number of items (sumitem).
```
with
member
sumitem
as
SUM ([FailureRea... | Just use
`[FailureReason].CurrentMember IS [FailureReason].[FailureReason].&[127]`
instead of
`[FailureReason].CurrentMember = [FailureReason].[FailureReason].&[127]`
and it will work.
**Update**: Several tips:
1. There is also not necessary to use `SUM` function, since you can define only tuple, this will be eno... | Try
```
with
member sumitem
as
SUM ([FailureReason].[FailureReason].[All],[Measures].[Items])
member LeaveOut
as
[FailureReason].[FailureReason].CurrentMember.Properties("Key")
member Impact
as
IIf([Measures].[LeaveOut]= "127", 0, [Measures].[Items]/[Measures].[SumItem])
``` | Set 0 for specific value MDX query | [
"",
"sql",
"sql-server-2008",
"ssas",
"mdx",
"cube",
""
] |
I have one Table in SQL Server 2008, like `T1, and have column like`C1 and C2`
I just want to swap values from `C1 to C2` and `C2 to C1`
for Example
```
C1 C2
-------- --------
12/11/2014 12/10/2014
12/13/2014 12/12/2014
12/15/2014 12/14/2014
12/17/2014 12/16/2014
12/19/2014 ... | Your query work for you..This is sample and give the perfect result.
```
declare @t table(c1 int, c2 int)
insert into @t values(10,11),(11,13),(14,15),(16,17),(18,19)
select * from @t
update @t set c1 = c2 ,c2=c1
select * from @t
```
Updated :- Please check my answer.
You can set dateformat in sqlserver side via `... | your query will work, if you want another method you can follow the below one
```
select* from tablename;
Go
DECLARE @tempcol as int
update tablename
set @tempcol= C1,
C1= C2,
C2= @tempcol
```
(if you have any conditions then )
WHERE condition;
GO
```
select* from tablename;
``` | How to Swap column values in SQL server of different datatype | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have four tables table\_1, table\_2, table\_3 and table\_4. All the four of them have columns like this:
```
table_1: age_grp, gender, height;
table_2: age_grp, gender, weight;
table_3: age_grp, gender, shoesize;
table_4: age_group, gender, BMI;
```
I would like to create a new table with columns:
```
age_grp, ge... | This easily can be doen via [`INNER JOIN`](http://dev.mysql.com/doc/refman/5.0/en/join.html):
```
SELECT table_1.*, table_2.*, table_3.*, table_4.* FROM table_1
INNER JOIN table_2 ON table_1.age_grp = table_2.age_grp
AND table_1.gender = table_2.gender
INNER JOIN table_3 ON table_2.age_grp = table_3.age_gr... | In spite of this request being answered already, I'd like to add an answer for the case of missing values, e.g. only shoesize not given for an age\_grp/gender pair.
For a solution with joins you would need FULL OUTER JOINs which MySQL doesn't support. And mimicking this with LEFT and /or RIGHT OUTER JOINs can be a pai... | How to merge multiple tables in MYSQl which have two columns in common | [
"",
"mysql",
"sql",
""
] |
How can I make a SQL query that returns me something like
```
---------------------
|DATE | Count |
---------------------
|2015/01/07 | 7 |
|2015/01/06 | 0 |
|2015/01/05 | 8 |
|2015/01/04 | 5 |
|2015/01/03 | 0 |
|2015/01/02 | 4 |
|2015/01/01 | 2 |
-... | One solution is to create a calendar table containing all the dates you need. You can then left join it to your data to get what you are after | You need a table of all the sequence numbers from 0 to 6. This is easy to generate in a simple query, as follows.
```
SELECT 0 AS seq
UNION ALL SELECT 1 UNION ALL SELECT 2
UNION ALL SELECT 3 UNION ALL SELECT 4
UNION ALL SELECT 5 UNION ALL SELECT 6
```
Next, let's... | Get last 7 days count even when there are no records | [
"",
"mysql",
"sql",
"laravel-4",
"aggregate-functions",
""
] |
i'v been learning SQL for the last week but I am unsure how to correctly add a case statement within a check constraint. Can anybody give me any pointers?
I have the following grade table:
```
CREATE TABLE Grade
(
salary_grade char(1) NOT NULL CHECK (salary_grade = UPPER(salary_grade)),
CONSTRAINT ck_g... | I think you can do the following:
```
CREATE TABLE Grade
(
salary_grade char(1) NOT NULL CHECK (REGEXP_LIKE(salary_grade, '[A-G]', 'c')),
salary_scale char(2) DEFAULT 'S1' NOT NULL,
CONSTRAINT pk_grade PRIMARY KEY (salary_grade),
CONSTRAINT ck_grade_scale CHECK ( REGEXP_LIKE(salary_grade, '[A-D]', 'c') A... | A `case` has to be compared to something, which is why you are getting the missing right parenthesis error. Unless you particularly want a `case`, you can just check the combination with and/or:
```
CONSTRAINT ck_grade_scale CHECK(
(salary_grade BETWEEN 'A' AND 'D' AND salary_scale = 'S1')
OR (salary_grade BET... | Using a case statement in a check constraint | [
"",
"sql",
"oracle",
"oracle11g",
"check-constraints",
""
] |
I have MySQL table
```
id product p_image
1 G images\20131030164545.jpg
2 S images\20131230164545.jpg
3 V images\20140110164545.jpg
4 R images\20140320164545.jpg
5 K images\20140526164545.jpg
6 L images\201... | Assuming the format of the string is fixed (which it looks to be) you can use the`substr`function to extract the timestamp and then cast it to a date and filter by it. Something like this should work:
```
select * from table1
where cast(substr(p_image FROM 7 FOR 14) as date)
between '2013/12/01' and '2014/07/30'
```
... | The dates in `p_image` are in YYYYMMDD format, so you can compare them as strings. That is, there is no reason to convert the strings to a date data type.
Hence you can just do:
```
where substr(p_image, 8, 8) between '20131201' and '20140730'
```
If the position of the date is not fixed but always after the `/`, yo... | Query to Select where timestamp between date1 and date 2 | [
"",
"mysql",
"sql",
""
] |
I use this forum all the time for VBA help but this is the first time I have to post something myself.
I am trying to make a report that provides a summary of various alarms stored in Access. I want to provide a simple Count of each alarm, each day. I have used some SQL queries but not really any Access. I took the fa... | So, I just wanted to add a header to my pivot table that would tell me what date the particular column was for.
The part of the code that I did not show was that I was using a rec.getrows to move all of my data into a simpler array variable. While this had all the data from Access, it did not have any headers to inform... | In order to get the records for all day, even those where there were no activity you need to create these days. The simplest way to do so in access is to use a set of UNION statements to create a fake table for the days similar to this:
```
SELECT #2015-01-20# as dt FROM dual
UNION ALL
SELECT #2015-01-21# as dt FROM d... | VBA Access Query for Day Summary | [
"",
"sql",
"excel",
"vba",
"ms-access",
"pivot",
""
] |
I have a column in SQL Server with utf8 SQL\_Latin1\_General\_CP1\_CI\_AS encoding. How can I convert and save the text in ISO 8859-1 encoding? I would like to do thing in a query on SQL Server. Any tips?
> Olá. Gostei do jogo. Quando "baixei" até achei que não iria curtir muito | I have written a function to repair UTF-8 text that is stored in a `varchar` field.
To check the fixed values you can use it like this:
```
CREATE TABLE #Table1 (Column1 varchar(max))
INSERT #Table1
VALUES ('Olá. Gostei do jogo. Quando "baixei" até achei que não iria curtir muito')
SELECT *, NewColumn1 = dbo.Dec... | [Jason Penny](http://jasontpenny.com/) has also [written](http://www.jasontpenny.com/blog/2009/07/31/sql-function-to-get-nvarchar-from-utf-8-stored-in-varchar/) an SQL function to convert UTF-8 to Unicode (MIT licence) which worked on a simple example for me:
```
CREATE FUNCTION dbo.UTF8_TO_NVARCHAR(@in VarChar(MAX))
... | Convert text value in SQL Server from UTF8 to ISO 8859-1 | [
"",
"sql",
"sql-server",
"encoding",
"utf-8",
"iso-8859-1",
""
] |
I'm a WPF developer not a sql dba... Trying to do a join in a sub select.
I have two tables: tbArticles & tbRegions. TbArticles holds a regionCode column which is also common to tbRegions. I'm trying to get a count of all articles by region and country:

from ises.tbarticles a
INNER JOIN ref.tbRegions r
On a.RegionCode = r.regionCode
group by r.longName, a.Country
order by longName
``` | Use need to use [GROUP BY Clause](http://www.techonthenet.com/sql/group_by.php) and then the count
```
Select r.longName, a.Country, Count(a.*) as ArticleCount
From ises.tbarticles a
INNER JOIN ref.tbRegions r On a.RegionCode = r.regionCode
Group By r.longName, a.Country
``` | T SQL: Inner join in sub select query? | [
"",
"sql",
"sql-server",
"join",
""
] |
I have this string:
Blah blah blah - 2389023823
I want to grab everything to the LEFT of the dash:
"Blah blah blah"
How do I go about doing this?
I'm assuming I would have to do `LEFT()` with `ChARINDEX() + LEN()` somehow but I'm having difficulty.
Appreciate the help. | You only need to use [LEFT](https://msdn.microsoft.com/en-us/library/ms177601.aspx) and [CHARINDEX](https://msdn.microsoft.com/en-us/library/ms186323.aspx):
```
SELECT LEFT(ColumnName, CHARINDEX('-', ColumnName)-1)
FROM TableName
``` | declare @string varchar(50)
set @string = 'Blah blah blah - 2389023823'
select SUBSTRING(@string, 1, NULLIF(CHARINDEX('-', @string) - 1, -1)) as ResultingString | How do I get a specific string UNTIL a specific character out of a string in SQL Server? | [
"",
"sql",
"sql-server",
"string",
""
] |
The incoming data Looks like this:
```
ID Key Year
1 2288 2013
1 2288 2014
1 2831 2012
1 3723 2012
1 5005 2012
```
The o/p should be
```
ID Key Year
1 2288 2013
1 2288 2014
```
If there are multiple "Key" Values" for the same ID and Year then those rows should ... | Group by ID and Year.
```
SELECT ID, MIN(KEY), YEAR
FROM TABLE
GROUP BY ID, YEAR
HAVING COUNT(KEY)=1
``` | Use `Window Function` to get the `min` key value in each `year` when it is duplicated.
```
Select ID, Key, Year from
(
select *,row_number() over(partition by Id,Year order by key) Rn
)a
where rn=1
``` | Select Unique rows from the data (not having mutiple Key values and Year) using SQL | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2012",
""
] |
So...this is a little confusing. I have 2 tables, one is basically a list of Codes and Names of people and topics and then a value, for example:

The second table is just a list of topics, with a value and a "result" which is just a numerical value t... | You can use Cross Apply here. There may be a better solution performance wise.
```
declare @people table(
Code int,
Name varchar(30),
Topic varchar(30),
Value int
)
declare @topics table(
[Subject] varchar(30),
Value int,
Result int
)
INSERT INTO @people values (1, 'Doe,John', 'History', 25),
(2, 'Doe,John', 'Geogra... | In this case I would make two joins instead of one. Something like this:
```
select *
from Table1 T1
LEFT JOIN Table2 T2 on T1.Topic=T2.subject and T1.Value=T2.VALUE
LEFT JOIN Table2 as T3 on T1.Topic=T3.Subject and T1.Value<T2.Value
```
The do a case to choose the table to take values from. If T2.value is null th... | LEFT OUTER JOIN...with differing matching keys | [
"",
"mysql",
"sql",
""
] |
I want the date in `DD-MMM-YYYY` format eg 29-JAN-2015.
I have tried with:
```
SELECT TRIM(TO_DATE('29 Jan 2015'
,'DD MON YY')) FROM DUAL
```
I got result as: 29-JAN-15
But I am expecting: `29-JAN-2015` in date format not in char format | Thanks for answers.
I got the solution. First we need to alter the session as below:
alter session set nls\_date\_format='DD-MON-YYYY';
then run the query:
SELECT TRIM(TO\_DATE('29 Jan 2015'
,'DD MON YYYY'))
FROM DUAL
Now I got result as:29-JAN-2015 | Im assuming Oracle DB:
```
select to_char(SYSDATE, 'dd-Mon-yyyy') from dual
```
Returns
```
29-Jan-2015
``` | How to format date in DD-MMM-YYYY format eg 29-JAN-2015? | [
"",
"sql",
"oracle",
"date",
""
] |
To describe my query problem, the following data is helpful:

A single table contains the columns ID (int), VAL (varchar) and ORD (int)
The values of VAL may change over time by which older items identified by ID won't get updated but appended. The ... | The correct way to select groupwise maximum in postgres is using [`DISTINCT ON`](https://stackoverflow.com/questions/9795660/postgresql-distinct-on-with-different-order-by)
```
SELECT DISTINCT ON (id) sysid, id, val, ord
FROM my_table
ORDER BY id,ord DESC;
```
[Fiddle](http://sqlfiddle.com/#!15/9afb5/3) | You want all records for which no newer record exists:
```
select *
from mytable
where not exists
(
select *
from mytable newer
where newer.id = mytable.id
and newer.ord > mytable.ord
)
order by id;
```
You can do the same with row numbers. Give the latest entry per ID the number 1 and keep these:
```
select... | Query historized data | [
"",
"sql",
"postgresql",
""
] |
```
For table1 Inserted 3 records
```
It should get those three identities and it should insert 3 records in table3 (but it’s not happening- it inserts 3 records with same identity ie.last scope identity)
```
create table table1(ID INT identity(1,1),Name varchar(50))
insert into table1 values('Ram'),('Sitha'),('... | Use the OUTPUT clause to handle multi-row inserts:
```
INSERT INTO dbo.table2(Name)
OUTPUT inserted.ID, inserted.Name INTO table3
SELECT Name FROM dbo.table1;
``` | You can use the OUTPUT clause to get the identity from any number of inserts.
```
create table table1(ID INT identity(1,1),Name varchar(50))
DECLARE @T1 Table (ID int, name varchar(50))
insert into table1
OUTPUT inserted.ID, Inserted.Name INTO @T1
values('Ram'),('Sitha'),('Laxman')
``` | Get Scope identity for multiple inserts | [
"",
"sql",
"sql-server",
""
] |
I found two solutions to this problem. One is hard to write and the other is slow to run. I was wondering if there's a better way I'm missing and I'm always happy to learn new methods.
I have an address table that holds multiple records for the same customer, but different types (billing, shipping, etc.) It might not ... | Not sure if this is faster:
```
select *
from (
select *,
row_number() over (partition by customer order by type) as rn
from personal
where type in ('billing', 'shipping')
)
where rn = 1;
```
This works because `'billing'` is ordered *before* `'shipping'` and thus gets the row number 1 if both address... | I would go with the second approach with two slight modifications. First, create an index on `customer` and `type`:
```
create index idx_personal_type_customer on personal(type, customer_type)
```
And use `union all` instead of `union`:
```
select *
from personal
where type = 'billing'
union all
select * from person... | Conditionally select entire record based on a field | [
"",
"sql",
"oracle",
""
] |
I am creating a query to get the total hours elapsed in a day by someone, however there can be multiple breaks in the times per day.
Here is the query that I have at the moment.
```
SELECT
CHINA_VISION_DorEvents.DorCtrls_Ref,
CHINA_VISION_PubCards.CardCode,
CHINA_VISION_DorEvents.EventTM
FROM
... | If you're not using a very old version of SQL Server, this will work for you:
Test Data:
```
CREATE TABLE Test(Ref int, CardCode varchar(20), EventTM datetime)
insert into Test
select 16,'000006f1','2015-01-27T07:32:35.000' union all
select 16,'000006f1','2015-01-26T07:38:02.000' union all
select 16,'000006f1','2015-... | From your result you have posted in your question, you can try the below code
```
CREATE TABLE #TEMP(Ref INT,CardCode VARCHAR(40),EventTM DATETIME)
INSERT INTO #TEMP
SELECT 16, '000006f1', '2015-01-27 07:32:35.000'
UNION ALL
SELECT 16, '000006f1', '2015-01-26 07:38:02.000'
UNION ALL
SELECT 16, '000006f1', ... | SQL Server, calculating total hours per day with multiple breaks | [
"",
"sql",
"sql-server",
""
] |
The CreatedDateTime is the table I am trying to filter by, using SQL
```
SELECT( * ) COUNT
FROM TABLE
WHERE CreatedDateTime like '2015''-''01''-''29%'
```
Return 0 Records
even though I have two records that have a CreatedDateTime of the following
```
CreatedDateTime
2015-01-29 07:33:25.700
2015-01-29 02:01:54.713
... | Datetime is not a string, Wildcard `%` is used to look for a pattern in a string value.
to get all the values in particular day you can simply cast it to date and that will ignore the time part and will bring back all the records for that particular date. Something like .....
```
SELECT COUNT(*)
FROM TABLE
WHERE CAST... | Assuming it's stored as a proper datetime you can strip the time portion and use equivalence, since wildcard matching is for strings:
```
SELECT COUNT(*)
FROM TABLE
WHERE CAST(CreatedDateTime AS DATE) = '2015-01-29'
``` | SQL filter by date returns 0 results | [
"",
"sql",
""
] |
I'm trying to create a view that returns the first occurrence of a value.
I have two tables
```
First table:
sID | dt
12 | DateTimeValue1
12 | DateTimeValue2
second table:
S_ID
12
```
I want the view to join both tables and give me the first occurance of S\_ID (in this case DateTimeValue1)
How can I accompl... | You could do something like : <http://sqlfiddle.com/#!3/66ee02/1>
```
create view theview as
select
t1.s_id, min(dt) dt
from
table1 t1 inner join
table2 t2 on t1.s_id = t2.s_id
group by
t1.s_id
``` | In MS SQL Server you can select the first row of table1 and join it with table2 in a view like this:
```
create view view_name
as
select table1.*,table2.*
from table2
inner join
(select top 1 *
from table1
order by table1.what_ever_field) as table1
on table2.id = table1.id
```
This wor... | Creating a View that returns the first occurrence of a value | [
"",
"mysql",
"sql",
"sql-server-2008",
""
] |
I have the following query
```
SELECT url
FROM
table_repo3
WHERE
(url LIKE '%auto%'
OR url LIKE '%automobile%'
OR url LIKE '%voiture%'
OR url LIKE '%bagnole%'
OR url LIKE '%vehicule%'
OR url LIKE '%berline%'
OR zpages LIKE '%auto%'
OR zpages LIKE '%automobile%'
OR zpages LIKE '%voiture%'
OR zpages LIKE '%bagnole%'
... | I think you want to do the following:
```
SELECT *
FROM table_repo3
WHERE url LIKE '%google%'
AND ( url LIKE '%auto%'
OR url LIKE '%automobile%'
OR url LIKE '%voiture%'
OR url LIKE '%bagnole%'
OR url LIKE '%vehicule%'
OR url LIKE '%berline%'
OR zpages LIKE '%auto%'
OR z... | You can do it simply using `SIMILAR TO` in `Postgres` for multiple `Like` checking, Try this way.
```
SELECT url
FROM
table_repo3
WHERE
url SIMILAR TO '%(auto|automobile|voiture|bagnole|vehicule|berline|google)%'
OR
zpages SIMILAR TO'%(auto|automobile|voiture|bagnole|vehicule|berline)%'
``` | why the or condition is not taken into account | [
"",
"sql",
"postgresql",
""
] |
I have the following schema:
```
PRODUCT_MASTER_TB
PRODUCT_CODE CATEGORY MODEL_GROUP
A 1 1
B 1 1
C 1 2
D 1 2
E 2 2
SALES_TB
SALES_DATE PRODUCT_CODE... | you can do aggregation based on `category` and `model_group` in a sub query and join with `product_master_tb`, using `left join` to get results for all products , if there is no quantity sold for the given date range, it will return zero for such products
```
select pmt.PRODUCT_CODE , isnull(t.soldqty,0) as SOLD_QTY_F... | This is a strange requirement, because you are a multiplying the total sum of `sold_qty`. The idea, though, is to append the category and model group and then group by that information:
```
select pm.PRODUCT_CODE, SOLD_QTY_FOR_CATEGORY_MODEL
from product_master_tb pm join
(select pm.category, pm.model_group,
... | SQL Select data based on the group of the product | [
"",
"sql",
"sql-server",
""
] |
I have two values in table PC and PC/name. But when I write a query,
```
select * from TransDetail TD where td.ModUserId like '%PC/%'
```
it gives me both results. Is there a way to get only one record? | You should make your WHERE clause like this:
```
select *
from TransDetail TD
where TD.ModUserId ='PC'
```
This way you will get the results which are matched to 'PC' **only**.
The *like* that you made is giving your results of cases that PC can be start/middle/end of the field | You should use this query instead for an exact match of the value PC:
```
SELECT * FROM TransDetail TD WHERE TD.ModUserId = 'PC';
```
When using % in the WHERE clause you are using a wildcard that stands for 0 or more occurrences of characters in that position.
Also, if you are actually using `LIKE '%PC/%'` it shoul... | How to do exact string match in SQL | [
"",
"mysql",
"sql",
""
] |
I want to create a column with a space in its name. In MySQL I just created this using back ticks, but in SQL Server that causes an error. Are there any possibilities to create a column name with a space?
I've tried the following but it doesn't work.
```
create table space_check
(
`roll num` int,
name varchar(50)
)
`... | Use brackets in SQL-Server
```
create table space_check
(
[roll num] int,
name varchar(50)
)
``` | Give the column name within `Square brackets`.
```
create table space_check
(
[roll num] int,
name varchar(50)
)
```
It was not a good practice. Try to create using underscore(roll\_num) or caps(rollNum). | How to create a column name with space in SQL Server | [
"",
"mysql",
"sql",
"sql-server",
"space",
""
] |
I'm using `sp_sqlexec` and was wondering how you deal with single quotes within the statement string **'problem'**
```
declare @id int =1
declare @sql nvarchar(200)
set @sql = '
insert into mytable (col1,col2) values (1, 'problem')
'
exec sp_sqlexec @sql
``` | Better than handling those extra quotes you could change your dynamic sql to use parameters. (Note this is using sp\_executesql instead of sp\_sqlexec because it allows for parameters)
```
declare @id int = 1
declare @sql nvarchar(2000)
declare @col2 varchar(10) = 'problem'
set @sql = 'insert into mytable (col1, col... | You can escape them with single quotes `'`:
```
set @sql = '
insert into mytable (col1,col2) values (1, ''problem'')'
```
[**SQLFiddle**](http://sqlfiddle.com/#!3/759a9c/1) | sql sp_sqlexec dealing with single quotes in statement | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Given the following schema...

how would I go about converting the following query to use joins (to work with MySQL)?
```
SELECT submissions.SubmissionID,
(SELECT data.DataContent FROM data WHERE data.DataFieldName =
(SELECT forms.FormEmailFieldName FROM forms WHERE f... | Starting from Olli's and Gordon's suggestions I have come up with the following which gives the same result set as my original query...
```
SELECT
s.SubmissionID,
d1.DataContent AS EmailAddress,
d2.DataContent AS Username
FROM submissions s
INNER JOIN forms AS f1 ON (f1.FormID = s.SubmissionFormID)
LEFT JOIN da... | Without having sample data, just a quick try:
```
SELECT
s.SubmissionID,
d1.DataContent AS EmailAddress,
d2.DataContent AS Username
FROM submissions s
JOIN forms AS f1 ON (f1.FormID = s.SubmissionFormID)
JOIN data AS d1 ON (d1.DataFieldName = f1.FormEmailFieldName)
JOIN data AS d2 ON (d2.DataFieldName = f1.Form... | Converting sub-queries to joins | [
"",
"mysql",
"sql",
"join",
"subquery",
""
] |
I have a database table with the columns: email, name, id
There are duplicate records with the same email and name (ids may or may not be different)
I want to remove all duplicates and not keep any of them.
Example
```
email | name | id
-------------------------------------------------
a@b.com ... | In MySQL, you should do this with a `join`:
```
delete t
from example t join
(select email, name
from example
group by email, name
having count(*) > 1
) todelete
on t.email = todelete.email and t.name = todelete.name;
```
Unfortunately, MySQL does not support simp... | You could use `EXISTS`:
```
DELETE FROM TableName t1
WHERE EXISTS
(
SELECT 1 FROM TableName t2
WHERE t1.id <> t2.id
AND COALESCE(t1.email,'') = COALESCE(t2.email,'')
AND COALESCE(t1.name,'') = COALESCE(t2.name,'')
)
```
I've used `COALESCE` to also delete duplicates if the emails or names ar... | How to remove ALL duplicates in a database table and NOT KEEP any of them? | [
"",
"mysql",
"sql",
""
] |
I have a query that returns multiple columns currently, below is an example.
What I am looking to do is count the number of times ClientID and ServerID pair up. I am looking to get the ServerID that most serves that Client.
```
ClientID, ServerID, Last.Date
1 AB 1/27/2015
2 DS ... | you can use `group by` and get maximum connections and then further do one more `group by` on the client to get the server that serves the most
**[SQL Fiddle](http://sqlfiddle.com/#!2/0bcbbb/3)**
```
SELECT clientId, serverId,
max(connectionCount) as ConnectionCount, LastDate
from
(
select clientId, ServerID,
count(... | You can `GROUP BY` multiple columns, to get the count of each combination.
```
SELECT ClientID, ServerID, MAX(`Last.Date`) AS `Last.Date`, COUNT(*) AS ConnectionCount
FROM YourTable
GROUP BY ClientID, ServerID
``` | SQL Count multiple columns | [
"",
"mysql",
"sql",
"count",
""
] |
I am using sql server 2008 R2. More specifically, Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64) Apr 2 2010 15:48:46 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows NT 6.1 (Build 7601: Service Pack 1) (Hypervisor). I am new to sql server and procedures/triggers. I have the following co... | ```
IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRIGGERNAME]'))
DROP TRIGGER [dbo].[TRIGGERNAME]
go
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[TABLENAME]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TRIGGER [dbo].[TRIGGERNAME] ON [dbo].[TABLENAM... | The best way is to check for objects and drop them if they exist before you create them.
Rather then not creating it at all if it exists, I would approach it the other way, drop it if exists and then create.
Normally in long lenghty scripts if you want to update the definition of a trigger you would just simply add t... | How to add "IF NOT EXISTS" to create trigger statement | [
"",
"sql",
"sql-server",
"t-sql",
"if-statement",
"triggers",
""
] |
I have an SQL selection which return the following:
```
Name Code Qty
Janet 10 6
Janet 11 9
Janet 09 8
Jones 12 7
Jones 11 8
James 09 5
James 10 4
```
I want this selection to get sorted based on the qty for all the three people : order the people by their maximum quantity, and... | You can specify more than one sorting condition:
```
SELECT * from names order by name, qty desc
```
Above query will sort by `name` and if names are equal then will sort by `qty`
If you want to select only higher qty for every user then use this query:
```
SELECT name, MAX(qty) FROM names GROUP BY name order by MA... | This is a subtle problem. It looks like you want to sort the *names* by the maximum of *qty*. This requires a join and aggregation to get the maximum `qty` for each `name`:
```
select t.*
from table t join
(select name, max(qty) as maxq
from table t
group by name
) tt
order by tt.maxq desc, tt.na... | Sort the SQL table by name using maximum of quantity | [
"",
"mysql",
"sql",
""
] |
Why correlated subquery result cannot be used in outer query?
In below query I want to access the count in the inner corrleated query in outer query. But it is giving error.
**What am I doing wrong?**
referenct - <http://sqlzoo.net/wiki/More_JOIN_operations#Looking_at_the_id_field>.
Question- 14 (Obtain a list in a... | `count` is a column in the subquery, but it is not part of the outer join. Therefore, it is not visible outside the subquery itself.
An easier way to tackle this would be by computing the count within your join itself, like so:
```
select a.name, count(movieid)
from
actor a
join casting c
on a.id = c.actorid
group b... | The question is asking two things. one for starring roles, two for at least 30 times. You can use WHERE to solve the first one, then group the result to count. Finally use HAVING to filter the second question.
You can use COUNT function in HAVING statement.
```
SELECT actor.name
FROM actor JOIN casting ON actor.id =... | Why correlated subquery result cannot be used in outer query? | [
"",
"sql",
"oracle",
"correlated-subquery",
""
] |
I am terrible with regex and too lazy to learn it (I know, it is bad...) My query
`SELECT regexp_replace('MYSTART1#blah~MYSTART2#blah2~MYSTART3#blah-blah~MYSTART4#blah-blah', '.*MYSTART2#(.+)\~.*', '\1') FROM DUAL;`
Should show the value between `MYSTART2#` and `~`
Result:
`blah2~MYSTART3#blah-blahMYSTART4#blah-blah... | The plus sign operator is "greedy," which means it matches as many characters as possible. Add a question mark to make it lazy instead:
```
'.*MYSTART2#(.+?)\~.*'
``` | Use regexp\_substr:
```
SELECT regexp_substr('MYSTART1#blah~MYSTART2#blah2~MYSTART3#blah-blah~MYSTART4#blah-blah', '[^\#\~]+', 1, 2*&mystart_pos) FROM DUAL;
``` | Extract text between two text delimiters (tags) | [
"",
"sql",
"regex",
"oracle",
""
] |
I have a table t1 with columns and rows as
```
date(date) plan(numeric) actual(numeric)
2015-01-01 50 36
2015-01-02 60 45
2015-01-03 70 40
2015-01-04 80 36
```
I want to change rows (only in plan column) with re... | ```
UPDATE t1 SET plan = 50 WHERE date >= '2015-01-01' AND date <= '2015-01-30'
``` | If I understand correctly, you want the first value of the month to be the value for the entire month.
With a query, you can do:
```
select date,
first_value(plan) over (partition by extract(year from date), extract(month from date)
) as plan,
actual
from t1;
``` | postgresql: update rows in a selected column with respect to date | [
"",
"sql",
"postgresql",
""
] |
I have the following query:
```
DECLARE @query AS NVARCHAR(MAX);
SET @query ='
SELECT
col1 [TÜR],
col2 [KOD],
col3 [BANKA/CARİ],
col4 [BANKA HESABI],
col5 [AÇIKLAMA],
col6 [VADE],
'+ @cols +'
FROM
(
(
SELECT
''LEASİNG'' [col1],
d.REGNR [col2],
cl.DEFINITION_ [col3],
'''' [col4],
d.DESCRIPTION [col5],
c.PAYM... | I have hit this before (albeit with varchar(max)). Below is the work-around we came up with. This is one of those situations where I can sorta understand why SQL does this, but I can't really explain it, let alone spell out precisely why it works this way. (Google around enough and you'll probably find a technical expl... | From [MSDN](https://msdn.microsoft.com/en-us/library/ms176047.aspx)
> A message string can be up to 8,000 characters long if it is a
> non-Unicode string, and 4,000 characters long if it is a Unicode
> string. Longer strings are truncated. The varchar(max) and
> nvarchar(max) data types are truncated to data types tha... | Query stored in NVARCHAR(MAX) does not fit | [
"",
"sql",
"sql-server",
"stored-procedures",
"nvarchar",
""
] |
```
create or replace procedure PROC_MYDATA (inputStr IN VARCHAR2,
p_RecordSet IN OUT SYS_REFCURSOR) is
begin
OPEN p_RecordSet FOR
(select * from myTable where name in (inputStr));
end PROC_MYDATA;
```
In the PLSQL Test window, I am trying to set,
inputStr = 'A','B'
and I am getting this error:
`... | I'm afraid it doesn't work this way:
```
SELECT * from myTable where name in (inputStr);
```
You can use dynamic SQL, as in @Bob Jarvis' answer, or you can do the following:
```
SELECT * FROM myTable WHERE REGEXP_LIKE(name, '^(' || REPLACE(inputStr, ',', '|') || ')$');
```
The difficulty with the latter is that, in... | To use a list of comma-separated values you'll need to build and execute the statement dynamically:
```
create or replace procedure PROC_MYDATA (inputStr IN VARCHAR2,
p_RecordSet IN OUT SYS_REFCURSOR)
is
strSql VARCHAR2(32767);
begin
strSql := 'select * from myTable where name in (' || inputStr || ')'... | comma separated parameter in plsql stored procedure | [
"",
"sql",
"oracle",
"plsql",
""
] |
I have two data sets: `DS_A` and `DS_B`.
My question is why I have two quantity for `pro_id` 71549 and not three?
The [ALL](https://msdn.microsoft.com/en-us/library/ms180026(v=sql.90).aspx)
Incorporates all rows into the results. This includes duplicates. If not specified, duplicate rows are removed.
```
loc_id ... | I suspect it is getting cast to int and rounded down
```
declare @tax float
set @tax = 0.05
declare @quantityF float
set @quantityF = 0.15
select @quantityF / @tax -- 3
select cast((@quantityF / @tax) as int) -- 2
```
You should not be using float - use decimal
```
declare @taxD decimal(9,2)... | Not sure ... works for me, on Oracle 11 ... what DBMS are you using, what version?
Seems like you might have a typo, or it's a 2 when you think it's a 3 ? It definitely should be a 3 after the UNION if it was a 3 before.
```
SQL> l
1 with w_d1 as (
2 select 2310 as loc_id, 5052 as pro_id, 1 as q... | WHY? UNION ALL is doing a Calculation | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2005",
""
] |
I am currently working on a project for the management of oil distribution, and i need the receipts of every bill to get stored in a database. I am thinking of building a smart key for the receipts which will contain the first 2 letters of the city, the gas station id, the auto increment number, first letter of the mon... | To answer the direct question - how to make the number restart at 1 at the beginning of the month.
Since it is not a simple `IDENTITY` column, you'll have to implement this functionality yourself.
To generate such complex value you'll have to write a user-defined function or a stored procedure. Each time you need a n... | Do you want to store all that in one column? That sounds to me like a composite key over four columns...
Which could look like the following:
```
CREATE TABLE receipts (
CityCode VARCHAR2(2),
GasStationId NUMERIC,
AutoKey NUMERIC,
MonthCode VARCHAR2(2),
PRIMARY KEY (CityCode, GasStationId, AutoKey, MonthCod... | How to create a smart key, which would reset its auto increment value at the end of the month | [
"",
"sql",
"sql-server",
""
] |
I'm having huge difficulty with a 3 table query.
The scenario is that `TEAM` has many or no `MEMBERS`, a `MEMBER` could have many or no `TASKS`. What I want to get is the number of `TASKS` for every `TEAM`. `TEAM` has its own `ID`, `MEMBER` holds this as a FK on `TEAM_ID`, `TASK` has `MEMBER_ID` on the `TASK`.
I want... | You want to use `count distinct`:
[MySQL COUNT DISTINCT](https://stackoverflow.com/questions/5737628/mysql-count-distinct)
```
select t.name as Team,
count(distinct m.ID) as Member_cnt,
count(distinct t.ID) as Task_cnt
from team t
left join member m
on t.ID= m.TEAM_ID
left join tasks t
on t.... | I think you can do what you want with aggregation -- and `count(distinct)`:
```
select t.name,
count(distinct m.memberid) as nummembers,
count(distinct tk.taskid) as numtasks
from team t left join
member m
on t.teamid = j.teamid left join
tasks tk
on tk.memberid = m.memberid
group by ... | 3 table query with count | [
"",
"mysql",
"sql",
"sqlplus",
""
] |
For example there is some table with dates:
```
2015-01-01
2015-01-02
2015-01-03
2015-01-06
2015-01-07
2015-01-11
```
I have to write SQL query, which will return the count of consecutive dates starting from every date in the table. So the result will be like:
```
2015-01-01 1
2015-01-02 2
2015-01-03 3
2015-01... | ```
CREATE TABLE #T ( MyDate DATE) ;
INSERT #T VALUES ('2015-01-01'),('2015-01-02'),('2015-01-03'),('2015-01-06'),('2015-01-07'),('2015-01-11')
SELECT
RW=ROW_NUMBER() OVER( PARTITION BY GRP ORDER BY MyDate) ,MyDate
FROM
(
SELECT
MyDate, DATEDIFF(Day, '1900-01-01' , MyDate)- ROW_NUMBER() OVER( ORDER BY MyDat... | You can use this `CTE`:
```
;WITH CTE AS (
SELECT [Date],
ROW_NUMBER() OVER(ORDER BY [Date]) AS rn,
CASE WHEN DATEDIFF(Day, PrevDate, [Date]) IS NULL THEN 0
WHEN DATEDIFF(Day, PrevDate, [Date]) > 1 THEN 0
ELSE 1
END AS flag
FROM (
SELECT [... | Get count of consecutive dates | [
"",
"sql",
"sql-server",
"date",
""
] |
I've got a table structure with 2 tables
a table person like this:
```
id name etc.
1 test
2 smith
3 shaw
```
and a second table personhist where I document the changes on the names like this: so if someone changed his name because he married or something like this I still got the old name.
```
id person... | > But I'd like to have only the actuel name result. So the question is is there a way to only show data from the "main" table also if there is a record in the table i join?
Simply do NOT include the columns which you don't want to display. You are using **SELECT \*** which is not actually a good thing to do on any pro... | ```
select p.*, coalesce(p.name, ph.name)
from person p
Left join personhist ph on p.id = ph.personid
where (upper(p.name) = upper('oldtest') or upper(ph.name) like upper('oldtest'))
``` | Selection with left join but without showing the Data inside the joined table | [
"",
"sql",
"oracle",
"select",
"join",
"left-join",
""
] |
I've been working lately in this and I couldn't work it out. I have the following table:
```
ID Language Text
---- -------- --------
1 spanish Hola
1 english Hello
2 spanish Chau
2 english Goodbye
2 french Au revoir
3 english Thank you
```
I need to get e... | This is another option:
```
SELECT i.ID, w.Text
FROM (
SELECT ID
FROM Words
GROUP BY ID) i(ID)
CROSS APPLY (
SELECT TOP 1 [Text]
FROM Words
WHERE ID = i.ID AND [Language] IN ('spanish', 'english')
ORDER BY (CASE [Language] WHEN 'spanish' THEN 1
... | For this type of prioritization, you can use `row_number()`:
```
Select t.*
From (select t.*,
row_number() over (partition by id
order by (case when Language = 'Spanish' then 1
when Language = 'English' then 2
... | SQL & SQL Server - Denormalized table, Distinct and Order By Complex Query | [
"",
"sql",
"sql-server",
"select",
"sql-order-by",
"distinct",
""
] |
I'm trying to run this SQL statement but seem to run into a error that states
> Msg 8120, Level 16, State 1, Procedure MemberCountryCarLocation, Line
> 5
> Column 'Country.Country\_name' is invalid in the select list because
> it is not contained in either an aggregate function or the GROUP BY
> clause.
Code:
```
... | If you use `group by` you can only select the column which are in the group by statement and aggregation function like `sum()`.
So you have to remove all values from `select` clause wich are not in `group by`
```
select M.member_Id
from Member M, Country C, License L, Addr A, Bz_Addr B
where M.member_id = A.member_id... | In this case, You need to add all the column names you are selecting when you use **group by**.
Try this:
```
create view MemberCountryCarLocation
(Member_ID, Country_Of_Rental, Home_Addr, Business_Name)
AS
select M.member_Id, C.country_name, A.addr1, B.business_addr
from Member M, Country C, License L, Addr A, Bz_A... | SQL Server error : can't seem to solve it | [
"",
"sql",
"sql-server",
""
] |
I have a table of some columns named as `Students`.
I am using following three queries to `select` rows.
```
1. select * from Students
2. select * from Students where 1=1
3. select * from Students where null=null
```
When I execute first then this returns all rows.
When I execute second then this is also returns... | To the questions part about "why" using this:
Since `1=1` always evaluates to `true` and `true` is the neutral element for logical `AND` operation, it is often used for dynamically built queries.
The problem with dynamically built queries that are using multiple `AND` operations added or not to the query on some con... | if you put `ANSI_NULL off` then it will return `true` . if it is `on` then it will return false
```
set ansi_nulls off
if null = null
print 'true'
else
print 'false'
set ansi_nulls ON
if null = null
print 'true'
else
print 'false'
```
reference got from [Null=Null](https://stackoverflow.com/questi... | What is 'where 1=1' and 'where null=null' in sql server | [
"",
"sql",
"sql-server",
""
] |
How to retrieve mysql distinct values without empty string value and NULL value
```
SELECT
DISTINCT CON.EMAILADDRESS AS 'E-MAIL'
FROM STUDENT
INNER JOIN CONTACT CON ON STUDENT.CONTACT_ID = CON.ID
WHERE
(CON.EMAILADDRESS IS NOT NULL
OR CON.EMAILADDRESS !=' ');
```
But in output still getting empty e-mails too. Can... | Try this:
```
SELECT
DISTINCT CON.EMAILADDRESS AS 'E-MAIL'
FROM STUDENT AST
INNER JOIN CONTACT CON ON AST.CONTACT_ID = CON.ID
WHERE length(trim(CON.EMAILADDRESS)) >0 and CON.EMAILADDRESS IS NOT NULL
``` | Your only problem is that you use OR instead of AND.
Let's look at the case where the value is NULL:
* `CON.EMAILADDRESS IS NOT NULL` => FALSE
* `CON.EMAILADDRESS != ' '` => NULL
FALSE OR NULL => NULL. As the criteria doesn't result in TRUE you don't select NULLs.
And if the value is an empty string '', ' ', or wha... | mysql distinct values without empty string and NULL | [
"",
"mysql",
"sql",
""
] |
My repeating table has duplicate ids but I want summary statistics on unique ids.
```
Detail_id code book tree
----------- ------ ------ ------
1 BR54 COOK PINE
1 BR55 COOK PINE
1 BR51 COOK PINE
2 BR55 COOK MAPL
2 BR60 COOK MAPL
3 ... | I don't think you need analytic functions here:
```
SELECT COUNT(DISTINCT CASE WHEN detail_book = 'COOK' THEN detail_id END) AS cook_total
, COUNT(DISTINCT CASE WHEN detail_book = 'FORD' THEN detail_id END) AS ford_total
, COUNT(DISTINCT CASE WHEN detail_tree = 'PINE' THEN detail_id END) AS pine_total
,... | You could use analytic functions and an inline view to avoid the duplicate counting issue:
```
select sum(case when detail_book = 'COOK' and book_cntr = 1 then 1 else 0 end) as cook_total,
sum(case when detail_book = 'FORD' and book_cntr = 1 then 1 else 0 end) as ford_total,
sum(case when detail_tree = '... | How to get summary totals on unique IDs using analytics? | [
"",
"sql",
"oracle",
"distinct",
"analytics",
""
] |
I have 2 tables.
```
Table 1:
ID Name Age PhoneNumber
12 Joe 25 873827382
23 Bob 28 928398233
34 Jane 23 237828883
Table 2:
ID Agent QuantitySold
12 A1 100
23 B1 300
12 C1 600
34 A2 ... | This is what finally worked.
```
SELECT a.ID
, a.Name
, a.Age
, a.PhoneNumber
FROM table1 a
WHERE a.ID NOT IN (SELECT ID FROM table2 QuantitySold = 800);
``` | You can use `NOT EXISTS` without any of the `JOIN`s:
```
SELECT a.ID
, a.Name
, a.Age
, a.PhoneNumber
FROM table1 a
WHERE NOT EXISTS (SELECT * FROM table2 WHERE ID = a.ID AND QuantitySold = 800)
```
By the way, the column name is `QuantitySold`, not `quantity`.
[**JSFiddle**](http://sqlfiddle.com/#!2/... | Left Join query not working | [
"",
"mysql",
"sql",
"join",
""
] |
In my project, I have two tables like this:
```
parameters (
id PRIMARY KEY,
name
)
```
and
```
parameters_offeritems (
id_offeritem,
id_parameter,
value,
PRIMARY KEY (id_offeritem, id_parameter)
)
```
*I'm not showing structure of `offeritems` table, because it's not necessary.*
Some sampl... | To get all parameters, plus the value of any parameters set for a specific Offer Item, you need to move the Offer ID logic into the join like this (see below).
```
SELECT p.*, p_o.value
FROM parameters p
LEFT JOIN parameters_offeritems p_o
ON p.id = p_o.id_parameter
AND id_offeritem = ... | The magic word you're looking for is OUTER JOIN. Jeff Atwood did a nice Venn-diagram explanation [here](http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/). | LEFT JOIN - fetching all data from left table with no matches in the right one | [
"",
"mysql",
"sql",
"left-join",
""
] |
I have table like this:
```
name | salary
Tom | 10000
Mary | 20000
Jack | 30000
Lisa | 40000
Jake | 60000
```
I need an update query to update the salary column depending on the values it contains.
Salaries need to increase by:
* 5000 for values between 10000 to 15000
* 7000 for values between 15000 to 20000
* 80... | Try using the [CASE](https://msdn.microsoft.com/en-us/library/ms181765.aspx) statement within the [UPDATE](https://msdn.microsoft.com/en-us/library/ms177523.aspx) command
```
UPDATE
[yourtablename]
SET
salary =
CASE
WHEN salary BETWEEN 10000 AND 15000 THEN salary + 5000
WHEN... | Something like this:
```
UPDATE YourTable
SET salary = CASE
WHEN salary > 10000 AND salary <= 15000 THEN salary + 5000
WHEN salary > 15000 AND salary <=20000 THEN salary + 7000
.
.
.
END
``` | Update table column values based on conditional logic | [
"",
"sql",
"sql-server",
"postgresql",
"t-sql",
"sql-server-2008-r2",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.