Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Can someone guide me on how to convert seconds into total hours, minutes and seconds format?
For example: 2,652,819 secs should give 736:53:39
I am able to get the same in `days:hours:minutes:seconds` format but I specifically require the convert the days also into total hours | Assuming you've got an integral value for `tot_secs` — floating point will require some judicious use of `round()`, `ceil()` and/or `floor()`, but you can try something like this:
```
select hours = ( t.tot_secs / 3600 ) , -- hours is total seconds / (secs/hr)
minutes = ( t.tot_secs % 3600 ) / 60 , -... | This will parse seconds into days:hours:minutes:seconds.
```
declare @seconds int = 2652819
select @seconds / (60 * 60 * 24) [days], (@seconds / (60 * 60)) % 60 [hours], (@seconds / 60) % 60 [minutes], @seconds % 60 seconds
select cast(@seconds / (60 * 60 * 24) as varchar(10)) + ':' +
cast((@seconds / (60 * 6... | Converting Seconds into Total Hours:minutes:seconds | [
"",
"sql",
"t-sql",
"sql-server-2008-r2",
""
] |
I'm trying to implement the search feature on my project,
so I add the class method :
```
class Donation < ActiveRecord::Base
belongs_to :member
def self.search_by_name name
includes(:member).where(member: { name: name } )
end
end
```
And I call it in the donatinos#index
```
cl... | As per Rails convention, table names are lower cased and pluralized model names so in the where clause you should specify `members` (in *plural*) and NOT `member` (in *singular*).
You can easily debug this looking at the error message: `SQLite3::SQLException: no such column: member.name`. With the error message, one c... | ```
def self.search_by_name name
includes(:member).where("members.name = ?", name)
end
```
Everything else stays the same . | The includes and where doesn't retrieve the correctly associated object | [
"",
"sql",
"ruby-on-rails",
"ruby",
"rails-activerecord",
""
] |
I am attempting to Use Bulk Insert to upload a very large data file (5M rows). All columns are just varchars no conversion. So the Format file is simple...
```
11.0
29
1 SQLCHAR 0 8 "" 1 AccountId ""
2 SQLCHAR 0 10 "" 2 TranDate ""
3 SQLCHAR 0 4 "" 3 TransCode "... | Explicitly state your row terminator:
```
BULK INSERT TableName FROM 'Path'
WITH (
DATAFILETYPE = 'char',
ROWTERMINATOR = '\r\n'
With (FORMATFILE = 'formatFilePPathSpecification')
);
```
If this still fails, check your file to see if you have unexpected terminators embedde... | If you still have problem even after enabling the errorfile output, you can do a binary search for the problem by setting the FirstRow and LastRow options and running bulk insert repeatedly to isolate the problem.
To be honest your input format looks so simple it might be a good idea to write a small C#, Python, or wh... | SQL Server Bulk Insert fixed width file failure | [
"",
"sql",
"sql-server",
"bulkinsert",
""
] |
I have this table [myTable] in SQL Server:
```
ID | Timestamp [datatype= datetime]
1 | 2013-08-05 23:09:02.000
2 | 2013-11-05 23:00:00.000
3 | 2013-08-05 23:09:02.000
4 | 2013-11-05 23:00:00.000
5 | 2014-01-01 22:00:00.000
```
In the table I have [sometimes] some duplicated timestamps. Using a SELECT statement, ... | ```
SELECT id, DATEADD(MILLISECOND,ROW_NUMBER() OVER (PARTITION BY Timestamp ORDER BY Id)-1,Timestamp) Timestamp
``` | ```
SELECT
DATEADD(ms,(ID*10),tbl.[TIMESTAMP]),tbl.*
FROM [TABLE] tbl
INNER JOIN (
SELECT
[TIMESTAMP],Count(*) [CNT]
FROM [TABLE]
GROUP BY [TIMESTAMP]
HAVING count(*)>1
) dupe ON dupe.[TIMESTAMP]=tbl.[TIMESTAMP]
``` | Duplicate Timestamps in SQL Server Query: How to add millisecond and avoid duplicates? | [
"",
"sql",
"sql-server",
""
] |
I am having getting the last sql to work.
The first two grouping gave me the right answer but the last one which involves joining 2 tables gave me a number thats too high when i manually add the first two together.
sql is to generate figures 1,2 and the (1+2) as 3.
Pls help.
sql below....
```
select [OrderDate... | Rather than try and get it in one you might want to try and sum an inline view of your UNION
```
SELECT
"Date",
"Payment Source",
SUM(Quantity) Quantity,
SUM("Value in Pounds") "Value in Pounds"
FROM
(
select [OrderDate] as "Date",
'Cobs' as "Payment So... | The way that you are doing your join
```
FROM cobaltins as cb
LEFT JOIN cobaltins_adhoc as cba
ON cb.OrderDate = cba.OrderDate
```
is only joining on the order date. if you have multiple orders per date then it's going to try to join those together arbitrarily. you will want to add something else into that join to ma... | sql to sum counts and add amounts from 2 tables | [
"",
"sql",
""
] |
I have a model named `Application`. And `Application` is associated to `has_many` model named `Location`.
`Application` has many `Location`
In my Application query:
```
$this->Application->find('all', array('conditions' => 'Application.status' => 'accepted'));
```
I'm finding `applications` where `status` is `accep... | You need to use a left join, not an inner join. Inner join will get only those results that have a row in both of the tables you are joining, where you want only results where there is only a row in the left table. Left joins will get all the results in the left table, regardless if there's a row associated with it in ... | Your query says "find any application and its location with application\_id = id, AND (1 OR where location.id = null)", so that will match any application that has location.
What I'd do is to leave joins and just use containable and counts. With plain sql I'd use a left join and count the `Locations`, like in [this ex... | Query to find where associated model (has many) is empty in cakephp | [
"",
"mysql",
"sql",
"cakephp",
""
] |
I have a CTE query that updates a single column in a table with approx 2.5 millions rows. I let the query run and it took about 16 hours!! How can I update this procedure so it will be faster? I read that SELECT INTO and create a new table should be a better way. I just dont know how to convert this CTE into a SELECT I... | It's possible to avoid calling the `CTE` twice by remodelling the query
```
UPDATE Cube2 SET
MonthlySales = CASE WHEN YEAR(cu.Period) = YEAR(cu.PayDate)
THEN cu.NySales
WHEN YEAR(cu.Period) <> YEAR(COALESCE(prev.Period, 0))
THEN cu.NS_Regu... | I don't think you need to reference the table three times. Your CTE is updatable, so I think the following is equivalent:
```
WITH CubeWithRowNumber AS (
SELECT c.*,
rownum = ROW_NUMBER() OVER (ORDER BY CustomerId, Period),
FROM Cube2 c
)
UPDATE CubeWithRowNumber crn
SET MonthlySale... | Convert CTE to better performing query | [
"",
"sql",
"sql-server",
"sql-server-2005",
"common-table-expression",
"database-performance",
""
] |
I have a table like this:

The `RP Type` column specifies the type of rate plan which can be (low, high, normal)
I want to create a view in which I can see number of each subscribers' which can be high, normal, low.
It should be like this I guess:
```
Create view t... | You can form your query in the following way:
```
SELECT SubID,
SUM (
CASE
WHEN RP_Type='High' THEN 1
ELSE 0 END
) AS NumOfHigh,
SUM (
CASE
WHEN RP_Type='Low' THEN 1
ELSE 0 END
) AS NumOfLow,
SUM (
CASE
WHEN RP... | i tried this :
```
select SubscriberID
,COUNT(*) AS NumOfPlans
,SUM([SP active days]) as ActiveDays
,SUM(Case when [RP Type]='low' then 1 else 0 end ) as #LowPlan
,SUM(Case when [RP Type]='high' then 1 else 0 end ) as #NormalPlan
,SUM(Case when [RP T... | Counting specific cells in SQL Server | [
"",
"sql",
"sql-server",
"count",
""
] |
I have 3 tables: user, recommendation (post\_id, user\_id), post
When a user votes on a post, a new recommendation record gets created with the post\_id, user\_id, and vote value.
I want to have a query that shows a random post that a user hasn't seen/voted on yet.
My thought on this is that it needs to join all rec... | There are several good ways to exclude rows that already have a recommendation from a given user:
[Select rows which are not present in other table](https://stackoverflow.com/questions/19363481/select-rows-which-are-not-present-in-other-table/19364694#19364694)
The important question is: **arbitrary** or **random**?... | You can do this with a left outer join:
```
SELECT p.*
FROM posts p LEFT OUTER JOIN
recommendations r
ON r.post_id = p.id and r.userid = YOURUSERID
WHERE r.post_id IS NULL
ORDER BY RANDOM()
LIMIT 1;
```
Note that I simplified the query by removing the double quotes (not needed for your identifier names) an... | postgresql query to determine recommendation records that haven't been seen by a user | [
"",
"sql",
"postgresql",
""
] |
I have hierarchical data that links instances of an entity using `DATE_FROM` and `DATE_TO`.
Please see [sqlfiddle](http://sqlfiddle.com/#!4/7c19c/1).
Using `CONNECT_BY` I can determine the number of contiguous instances for each entity, i.e., the length of the "islands", which is mostly what I want. E.g., this gives ... | A WHERE-condition is evaluated after CONNECT BY, so your query does not start with the rows from 2014. It creates the hierarchy for each and every row in your table, you can easily see that when you remove the WHERE and the aggregation:
```
SELECT
T.ENTITY_ID,
LEVEL,
T.DATE_TO,
T.DATE_FROM,
prior T.DATE_T... | Your sql statement is correct. But one scenario that needs to be considered when `CASE WHEN T.DATE_TO - PRIOR T.DATE_FROM > 183` statement becomes `null` which will not be counted.
```
INSERT INTO TEST
VALUES (1,TO_DATE('20130101','YYYYMMDD'),TO_DATE('20140101','YYYYMMDD'));
INSERT INTO TEST
VALUES (1,TO_DATE('201... | Counting Rows with Constraint in Hierarchical Data | [
"",
"sql",
"oracle",
"hierarchical-data",
"gaps-and-islands",
""
] |
I need to get all company ids from a table that have both city ids (let's say 7333 and 10906) but id doesn't work the way I do it.
This is my table:

and this is my code
```
SELECT `company_id` as id
FROM `logistics_companies_destinations`
... | You can also solve this using an `INNER JOIN` to the table itself, joining on the same `company_id` and requiring both city\_ids to be present:
```
SELECT
`lcd1`.`company_id` AS id
FROM `logistics_companies_destinations` AS lcd1
INNER JOIN `logistics_companies_destinations` AS lcd2
WHERE `lcd1`.`city... | MySQL does not have an `INTERSECT` keyword, but one way to implement this is:
```
SELECT `company_id` as id
FROM `logistics_companies_destinations`
WHERE
`city_id` = 10906
and `company_id` IN (SELECT `company_id` as id
FROM `logistics_companies_destinations`
... | get all rows from table that have both variables in a same column | [
"",
"mysql",
"sql",
""
] |
Im hoping this is a straight forward question but I cannot work out the syntax for it.
I just need to find if a value within "ID" also exists in "ID2", lets say the tables called "teacher"
```
ID-ID2
10-1
11-2
12-13
13-4
```
the only match there is row 4 as 13 also exists in id2, so I would need to pull that out wit... | Is this what you want?
```
select t.*
from teacher t
where exists (select 1 from teacher t2 where t2.id = t.id2);
``` | ```
select *
from teacher
where id in (select distinct id2 from teacher)
```
or
```
select t1.*
from teacher t1
join teacher t2 on t1.id = t2.id2
``` | sql compare two unique rows from the same table | [
"",
"sql",
""
] |
I have the following 2 tables.
First is: `idea_box`

Second is: `idea_box_voting`

Now I want result something like this, based on `0 and 1 count`from thumbs field.
![enter image... | Try this:
```
SELECT a.idea_id, a.property_id, a.the_idea, a.user_id, a.added_date, a.status,
SUM(b.thumbs = 1) AS up, SUM(b.thumbs = 0) AS down
FROM idea_box a
LEFT JOIN idea_box_voting b ON a.idea_id = b.idea_id
GROUP BY a.idea_id;
``` | SELECT t1.\*,sum(t2.thumbs=1) as up,sum(t2.thumbs=0) as down FROM table1 as t1 left join table2 as t2 using(idea\_id) group by t1.idea\_id; | MYSQL get spacific table fields counts | [
"",
"mysql",
"sql",
"select",
"group-by",
"sum",
""
] |
===== EDIT: Modified original question =====
Based on the comments, I have edited the original question (I left the original question at the end) as follows:
I have sample employee data stored in a table (emp) like this:
```
ID | Key | Value
1000 | 1 | Engineer
1000 | 2 | Male
1000 | 3 | 30
1001 | 1 | Mana... | You can do this by first aggregating by the employee id and then reaggregating:
```
select type,
count(*) as num,
sum(case when sex = 'male' then 1 else 0 end) as males,
sum(case when sex = 'female' then 1 else 0 end) as females,
avg(cast(age as decimal(5, 2))) as avgage
from (select employ... | You should group by type and then use aggreagate functions with accurate conditions:
```
SELECT
type,
COUNT(*) AS count,
COUNT(CASE WHEN Sex = 'Male' THEN 1 ELSE NULL END) AS number_of_males,
COUNT(CASE WHEN Sex = 'Female' THEN 1 ELSE NULL END) AS number_of_females,
AVG(age) AS avg_age
FROM employ... | Select averages in each GROUP BY group? | [
"",
"sql",
"oracle",
"count",
"group-by",
"aggregate-functions",
""
] |
I want to align a column in my table. In this case 'Title'
```
mysql> SELECT Titel, KuenstlerName from Bild;
+--------------------------+---------------+
| Title | Artist|
+--------------------------+---------------+
| Drei Musikanten | Picasso |
| Buveuse assoupie | P... | If your `Title` length is 150 then query like this
```
SELECT LPAD(Titel,150,' ') as Titel , KuenstlerName from Bild;
```
Check [**Manual**](http://www.w3resource.com/mysql/string-functions/mysql-lpad-function.php) for `LPAD` function. | If `Titel` is 100 characters, then do this
```
SELECT
LPAD(Titel, 100, ' '),
...
```
or
```
SELECT
RIGHT(CONCAT(REPEAT(' ', 100), Titel), 100),
...
``` | How to align a column right-adjusted | [
"",
"mysql",
"sql",
"select",
"format",
"tabular",
""
] |
I am using SQL Server 2008 R2 on the EC2 instance. I have a database having 4 fields of all varchar(50).
```
SELECT
*
FROM
xyz
WHERE
DataDate ='20140609'
```
This query gives no result.
```
SELECT
*
FROM
xyz
WHERE
DataDate = (Select MAX(DataDate) from xyz)
```
This query runs perfectly.
```
Select MAX(DataD... | As stated in comments it's likely due to leading spaces in the values. If you do the following to remove any spaces from the values it should work:
```
SELECT *
FROM xyz
WHERE REPLACE(DataDate, ' ', '')='20140609'
```
Alternately, you could use [**LTRIM**](http://msdn.microsoft.com/en-gb/library/ms177827.aspx) / [**... | in sql spaces count as the character. Then use like operator to this query as
SELECT
\*
FROM
xyz
WHERE
DataDate like '%20140609%' | Filter dates stored as varchar in SQL Server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
""
] |
Say I have the following data set
```
Column1 (VarChar(50 or something))
Elias
Sails
Pails
Plane
Games
```
What I'd like to produce from this column is the following set:
```
LETTER COUNT
E 3
L 4
I 3
A 5
S 5
And So On...
```
One solution I thought of was combining al... | I would do this by creating a table of your letters similar to:
```
CREATE TABLE tblLetter
(
letter varchar(1)
);
INSERT INTO tblLetter ([letter])
VALUES
('a'),
('b'),
('c'),
('d'); -- etc
```
Then you could join the `letters` to your table where your data is like the letter:
```
select l.letter, ... | If you create a table of letters, like this:
```
create table letter (ch char(1));
insert into letter(ch) values ('A'),('B'),('C'),('D'),('E'),('F'),('G'),('H')
,('I'),('J'),('K'),('L'),('M'),('N'),('O'),('P')
,('Q'),('R'),('S'),('T'),('U'),('V'),('W'),('X'),('Y'),('Z');
```
you could do it with a cross join, like th... | Count Of Distinct Characters In Column | [
"",
"sql",
"sql-server",
"count",
"distinct-values",
""
] |
How do I get the average from multiple columns?
for example:
```
Columns: ID 125Hz 250Hz 500Hz 750Hz 1000Hz 1500Hz 2000Hz 3000Hz 4000Hz 6000Hz 8000Hz
Values: 1 92 82 63 83 32 43 54 56 54 34 54
```
I want to get the average of all the columns except the ID. How do I do tha... | You have to manually add the columns since there's no available built-in functions for horizontal aggregation.
```
select (125Hz+250Hz+500Hz+750Hz+1000Hz+1500Hz+2000Hz+3000Hz+4000Hz+6000Hz+8000Hz)/11 as aveHz from table_name
``` | In SQL-SERVER you can use this
```
DECLARE @total int
DECLARE @query varchar(550)
DECLARE @ALLColumns VARCHAR(500)
SET @ALLColumns = ''
----Build the string columns
SELECT @ALLColumns = @ALLColumns + '+' + '['+sc.NAME+']'
FROM sys.tables st
INNER JOIN sys.columns sc ON st.object_id = sc.object_id
WHERE st.name L... | SQL average from multiple columns | [
"",
"mysql",
"sql",
"sql-server",
"mysql-workbench",
""
] |
I just learned about the wonders of columnstore indexes and how you can "Use the columnstore index to achieve up to 10x query performance gains over traditional row-oriented storage, and up to 7x data compression over the uncompressed data size."
With such sizable performance gains, is there really any reason to NOT u... | The main disadvantage is that you'll have a hard time reading only a part of the index if the query contains a selective predicate. There are ways to do it (partitioning, segment elimination) but those are neither particularly easy to reliably implement nor do they scale to complex requirements.
For scan-only workload... | Columnstore Indexes is especially beneficial for **DataWarehousing (DW)**. Meaning that you will only perform updates or deletes at certain times.
This is due to their special design with delta loading and more features. This video will show great detail and a nice basic overview of what the exact difference is [Colum... | Columnstore index proper usage | [
"",
"sql",
"sql-server",
"database",
"t-sql",
"optimization",
""
] |
I know there is no "last" row so I hope I'm clear that isn't what I'm really looking for. I want to select the rows in a table if the value of one particular field is the last alphabetically. I'll try my best to draw it out below. I'm a bit of a novice so please bear with me...
TABLE
[Order Number], [Delivery Date], [... | It possible to use the `ROW_NUMBER` function to get the last row in a group setting the `ORDER BY` descending and then using a filter to get the row with the value 1.
The `SUM` and `MAX` with windowing help to get the other aggregate values.
```
WITH D AS (
SELECT [Order Number]
, [Delivery Date]
, SUM... | Is this what you're going after?
**EDIT 2:** Got clarification from OP. Have edited my solution to bring up aggregation for complete order but only the line item information of the latest invoice. Fiddle here: <http://sqlfiddle.com/#!3/08bb0/6>
```
SELECT t1.[Order Number],
t2.[Max Invoice Number],
t1.[... | Find the most recent row of a group | [
"",
"sql",
"sql-server-2008-r2",
""
] |
I'm trying to fetch some data from an db. I've got an `Taak` table with an possible `idPartij` column. Possible, because it can be an real `idPartij`, but can also be `null`.
The query I've got:
```
SELECT T.idTaak,
T.Taaktype,
P.Partijnaam,
T.Naar,
T.UltimatumDatum,
T.Opmerking,
... | Since you are trying to link two tables, you should use a `LEFT OUTER JOIN` instead:
```
SELECT T.idTaak,
T.Taaktype,
P.Partijnaam,
T.Naar,
T.UltimatumDatum,
T.Opmerking,
T.Status,
T.Prioriteit
FROM Taak AS T LEFT OUTER JOIN Partij AS P
ON T.idPartij = P.idPartij
ORD... | You didn't specify a database platform, so it is safe to use ANSI syntax.
Do a `coalesce` to compare `P.idPartij` when `T.idPartij` is `null`:
```
where P.idPartij = coalesce(T.idPartij, P.idPartij)
```
It will match all `T` rows if `T.idPartij` is `null`.
If you want to return no `T` row when `idPartij` is `null`,... | SQL Where ID equals ID but can be null | [
"",
"sql",
"where-clause",
""
] |
Say we have a simple table of blog articles, for example:
```
aid title content
1 Foo Lorem Ips…
2 Bar Dolor Sit…
3 Boo Amet Cons…
```
… and another table for the comments:
```
cid aid name comment date
1 1 zaphod First! 1404294939
2 1 arthur Not ... | The methodology needed is to first find the latest comment date per article:
```
SELECT aid, MAX(Date) AS Date
FROM Comments
GROUP BY aid;
```
You can then place this logic inside a subquery and join back to comments using `aid` and `date` to get all the fields:
```
SELECT c.*
FROM Comments AS c
INNE... | You can do this using joins only.It is much faster than Sub query.
```
select articles.*,comments1.* from
Articles articles
LEFT JOIN (Comments comments1
LEFT JOIN Comments comments2 on comments1.date<comments2.date
and comments1.aid=comments2.aid
) on comments2.cid IS NULL and comments1.aid=article... | MySQL Join left row with only the first right row | [
"",
"mysql",
"sql",
"join",
"relational-database",
""
] |
I have a table with sell orders and I want to list the `COUNT` of sell orders per day, between two dates, without leaving date gaps.
This is what I have currently:
```
SELECT COUNT(*) as Norders, DATE_FORMAT(date, "%M %e") as sdate
FROM ORDERS
WHERE date <= NOW()
AND date >= NOW() - INTERVAL 1 MONTH
GROUP BY DA... | Creating a range of dates on the fly and joining that against you orders table:-
```
SELECT sub1.sdate, COUNT(ORDERS.id) as Norders
FROM
(
SELECT DATE_FORMAT(DATE_SUB(NOW(), INTERVAL units.i + tens.i * 10 + hundreds.i * 100 DAY), "%M %e") as sdate
FROM (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 ... | You are going to need to generate a virtual (or physical) table, containing every date in the range.
That can be done as follows, using a sequence table.
```
SELECT mintime + INTERVAL seq.seq DAY AS orderdate
FROM (
SELECT CURDATE() - INTERVAL 1 MONTH AS mintime,
CURDATE() AS maxtime
... | Aggregating data by date in a date range without date gaps in result set | [
"",
"mysql",
"sql",
"time-series",
"mariadb",
""
] |
Consider these two PostgreSQL functions:
```
CREATE OR REPLACE FUNCTION f_1 (v1 INTEGER, v2 OUT INTEGER)
AS $$
BEGIN
v2 := v1;
END
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION f_2 (v1 INTEGER)
RETURNS TABLE(v2 INTEGER)
AS $$
BEGIN
v2 := v1;
END
$$ LANGUAGE plpgsql;
```
In any "ordinary" procedural SQL lan... | `\df public.f_*` does this
```
select
n.nspname as "Schema",
p.proname as "Name",
pg_catalog.pg_get_function_result(p.oid) as "Result data type",
pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types",
case
when p.proisagg then 'agg'
when p.proiswindow then 'window'
... | It *appears* that the `pg_catalog.pg_proc.proretset` flag contains a *hint* about whether the function returns a set (i.e. a table):
```
SELECT r.routine_name, r.data_type, p.parameter_name,
p.data_type, pg_p.proretset
FROM information_schema.routines r
JOIN information_schema.parameters p
USING ... | Is there any formal difference at all between PostgreSQL functions with OUT parameters and with TABLE results? | [
"",
"sql",
"postgresql",
"stored-procedures",
"user-defined-functions",
"out-parameters",
""
] |
I have two tables that names StationTabs and Links in SQLServer2008.
```
StationTabs
------------
StationId(int)
Longitude(float)
Latitude(float)
Links
----
id(int)
StationStart(int)
StationEnd(int)
```
StationStart and StationEnd are foreign keys of StationId. I should get Longitude and Latitude values for Station... | If you're wanting to get the start and end lat/long values for each `Links` entry, you're doubling-up references to the wrong table:
```
SELECT
ST1.Longitude as StartLong,
ST1.Latitude as StartLat,
ST2.Longitude as EndLong,
ST2.Latitude as EndLat,
l.ID as LinkID
FROM
Links l
inner join
... | This should work:
```
SELECT Longitude,
Latitude
FROM StationTabs st
INNER JOIN Links lStart
ON st.StationId = lStart.StationStart
INNER JOIN Links lEnd
ON st.StationId = lEnd.StationEnd
```
If one of both (or both) can be null but you want to include this record anyway you should use `LEFT OUTER J... | Properly Joining Tables in SQL | [
"",
"sql",
"sql-server-2008",
""
] |
I want to select 1000 rows from another table using the last 1000 ID from another table. This is the query but it returned an error message. What did I do wrong with this query?
```
SELECT * FROM table1
WHERE id IN
(
SELECT id FROM table2
LIMIT 50
)
```
Error message received.
```
Error Code : 1235
This version of M... | ```
SELECT *
FROM table1 x
JOIN
( SELECT id FROM table2 ORDER BY id LIMIT 50 ) y
ON y.id = x.id;
``` | You should join both tables and sort in descending order and *then* apply the limit.
```
SELECT table1.* FROM table1
JOIN table2 USING (id)
ORDER BY id DESC
LIMIT 1000;
```
This will give you 1000 entries with highest `id`in descending order if, and only if, they exist in both tables. | SELECT ID FROM subquery with limit 1000 rows in MySQL | [
"",
"mysql",
"sql",
"subquery",
""
] |
I have a a number of sp's that create a temporary table `#TempData` with various fields. Within these sp's I call some processing sp that operates on `#TempData`. Temp data processing depends on sp input parameters. SP code is:
```
CREATE PROCEDURE [dbo].[tempdata_proc]
@ID int,
@NeedAvg tinyint = 0
AS
BEGIN
SET... | The way that stored procedures are processed is split into two parts - one part, checking for syntactical correctness, is performed at the time that the stored procedure is created or altered. The remaining part of compilation is deferred until the point in time at which the store procedure is *executed*. This is refer... | Create the table with the column initially. If you're populating the TEMP table with SPROC output just make it an IDENTITY INT (1,1) so the columns line up with your output.
Then drop the column and re-add it as the appropriate data type later on in the SPROC. | StoredProc manipulating Temporary table throws 'Invalid column name' on execution | [
"",
"sql",
"t-sql",
"sql-server-2005",
"tempdata",
""
] |
Consider the following:
```
class User < ActiveRecord::Base
has_many :events
end
class Event < ActiveRecord::Base
belongs_to :user #this user is the event owner
has_many :members
end
class Members < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
```
Now, I need to list all the members for which... | Add a has\_many :through association to your User model:
```
class User < ActiveRecord::Base
has_many :events
has_many :members, :through => :events
end
```
Now you can query for all a user's members through the members association:
```
user.members
```
The SQL generated will look something like:
```
SELECT "m... | I guess this will work.
```
Member.joins(:event).where("events.user_id = ?" , current_user.id)
``` | How to write this ActiveRecord Query using Join instead of subquery in Rails 4 | [
"",
"sql",
"ruby-on-rails",
"postgresql",
"activerecord",
"ruby-on-rails-4",
""
] |
I'm working on a project and need some help trying to get this XML query to work. I'm trying to query the XML below in SQL as a new column "Company" with the Company values.
The column name is `CustomData` and is varchar(3000) so it looks like it needs to be converted to XML, unless there is another way to do this.
`... | I managed to get it working by using the code below. Not sure why but it looks like my XML is actually UTF-16 and not UTF-8, which might've been giving me problems as well. Thanks for the help.
```
CAST(CAST(CustomData AS NTEXT) AS XML).value('(/ArrayOfCustomData/CustomData[@name="Company"]/@value)[1]','varchar(3000)'... | Your XPath is invalid, try this way instead :
```
select
CustomData.value('(/ArrayOfCustomData/CustomData[@name="Company"]/@value)[1]','varchar(30)') as Company
from tbl_User_Ref
```
Notice the use of `@` at the beginning of attribute name to address an XML attribute, and the use of expression within square-brac... | SQL Query - Querying XML, having issues | [
"",
"sql",
"xml",
""
] |
I have a table with hierarchical data in it, the structure goes like this:
```
ID ParentId
---- ----------
1 NULL
2 1
3 2
4 2
5 3
6 5
```
If I pass the node Id I would like to get the top most node Id/details by traversing through all its parents in SQL.
I tried CTE, i some... | ```
DECLARE @id INT = 6
;WITH parent AS
(
SELECT id, parentId, 1 AS [level] from tbl WHERE id = @id
UNION ALL
SELECT t.id, t.parentId, [level] + 1 FROM parent
INNER JOIN tbl t ON t.id = parent.parentid
)
SELECT TOP 1 id FROM parent ORDER BY [level] DESC
```
@TechDo's answer assumes the lowest ID will... | Please try:
```
declare @id int=6
;WITH parent AS
(
SELECT id, parentId from tbl WHERE id = @id
UNION ALL
SELECT t.id, t.parentId FROM parent
INNER JOIN tbl t ON t.id = parent.parentid
)
SELECT TOP 1 id FROM parent
order by id asc
``` | Get Root parent of child in Hierarchical table | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
""
] |
Confused on why this happens. I have a query that is excluding records that I want to include.
The record in question has these values:
```
MEMBER_ID NAME_FIRST NAME_LAST START_DATE END_DATE PROGRAM_ID INDICATOR
-------------------- -------------------- ------... | Use Trunc() function to truncate the time associated with the date. Then only the dates can be compared as per your requirement. | The last line, looks as :
```
AND (HDATE.END_DATE IS NULL OR HDATE.END_DATE>=LAST_DAY(ADD_MONTHS(SYSDATE,-2)))
30-APR-14-00.00:00 >= 30-JUN-14-09.xx:xx (it includes the time part),
```
therefore it returns FALSE and you don't get the record.
To truncates the time part use TRUNC() function:
```
AND (HDATE.END_DATE ... | Need help querying Oracle date field | [
"",
"sql",
"oracle",
""
] |
I have a `TABLE` with Columns: `USER_ID`,`TIMESTAMP` and `ACTION`
Every row tells me which user did what action at a certain time-stamp.
**Example:**
* Alice starts the application at 2014-06-12 16:37:46
* Alice stops the application at 2014-06-12 17:48:55
I want a list of users with the time difference between the... | I think you should group this table by USER\_ID and find minimum date of "START\_APP" and maximum of "CLOSE\_APP" for each user. Also you should use in [DATEDIFF](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff) the CLOSE\_APP time first and then START\_APP time in this case you wi... | ```
SELECT user_id, start_time, close_time, DATEDIFF(close_time, start_time) duration
FROM
(SELECT MIN(timestamp) start_time, user_id FROM MOBILE_LOG WHERE action="START_APP" GROUP BY user_id) start_action
JOIN
(SELECT MAX(timestamp) close_time, user_id FROM MOBILE_LOG WHERE ACTION ="CLOSE_APP" GROUP BY user_id... | MySQL Date difference between two rows | [
"",
"mysql",
"sql",
"row",
"datediff",
""
] |
I have a simple table with the following
```
TABLE Color(
Color_id int IDENTITY(1,1) NOT NULL PRIMARY KEY,
Coloring_type [varchar](20) NULL,
ColorA int NOT NULL,
ColorB int NULL,
ColorC int NULL)
```
and I want to execute the following query to insert some data and return the Inserted Color\_id to... | You can try using the following one,
```
IF EXISTS (SELECT Color_id
FROM Color
WHERE Coloring_type = 'solid' AND ColorA = 'red' AND
ColorB = 'green' AND ColorC = 'blue')
BEGIN
SELECT Color_id
FROM Color
WHERE Coloring_type = 'solid' AND ColorA = ... | You can check for existence of a record with an [`EXISTS`](http://msdn.microsoft.com/en-us/library/ms188336.aspx) check beforehand and then execute code based on the result.
You can output the id in 2 ways, with an output parameter or the easiest way would be a simple `SELECT` and in C# you would call [`.ExecuteScalar... | SQL output the id of inserted new data or output the id if duplicated without insertion | [
"",
"sql",
"sql-server",
""
] |
Hi I try to implement sql cipher. I use the code from github from here(<https://github.com/sqlcipher/android-database-sqlcipher>). Extract the source code and import it into eclipse. But it's not running. I got the following exception . Please anyone tell me what i've done wrong?
```
FATAL EXCEPTION: main
java.lang.U... | I found the solution:
Initially i forgot to add `armeabi`, `armeabi-v7a`, `x86` folders. Which contains .so files.
In `armeabi`:
```
libdatabase_sqlcipher.so
libsqlcipher_android.so
libstlport_shared.so
```
In `armeabi-v7a`:
```
libdatabase_sqlcipher.so
libsqlcipher_android.so
libstlport_shared.so
```
In `x86`:
`... | Your project is not properly including the native .so files with your application. These are required for SQLCipher for Android to operate. They should be in a platform specific folder beneath the `libs` folder. As a reference, please review the project structure of the SQLCipher for Android [test suite](https://github... | Implement sqlcipher-for-android | [
"",
"android",
"sql",
"sqlcipher",
""
] |
Given the following body of a case statement:
```
1 WHEN r.code= '00' then 'A1'
2 WHEN r.code ='01' AND r.source = 'PXWeb' then 'A2' <
3 WHEN r.code ='0120' then 'A3'
4 WHEN r.code ='01' then 'A4' <
5 WHEN r.code ='1560' ... | The value that is returned will be the value of the `THEN` expression for the earliest `WHEN` clause (textually) that matches. That does mean that if your line 2 conditions are met, the result will be `A2`.
But, if your `THEN` expressions were more complex than just literal values, some of the work to *evaluate* those... | Never mind:
"The CASE statement evaluates its conditions sequentially and stops with the first condition whose condition is satisfied."
<http://msdn.microsoft.com/en-gb/library/ms181765.aspx> | Execution order of WHEN clauses in a CASE statement | [
"",
"sql",
"case",
"sybase",
"case-when",
""
] |
I got three columns with binary values. Then i got a query which makes a string based on those values. I made this work using `case`. But it's quite huge (it's a part of a bigger query), and i was wondering maybe there is a better way of doing this?
```
SELECT (CASE
WHEN TableA.flag1 = 1 AND TableA.flag2 = 1 AND T... | You can use `left()` instead.
```
select left('C', T.flag1)+
left('G', T.flag2)+
left('R', T.flag3)
from TableA as T
``` | I don't know if this is "better" but it is more concise:
```
SELECT ((CASE WHEN TableA.flag1 = 1 THEN 'C' ELSE '' END) +
(CASE WHEN TableA.flag2 = 1 THEN 'G' ELSE '' END) +
(CASE WHEN TableA.flag3 = 1 THEN 'R' ELSE '' END)
)
FROM TableA;
```
Okay, this isn't exactly the same because you get `''... | Replacing CASE in SQL query | [
"",
"sql",
"sql-server",
"case",
""
] |
I have a daily sessions table with columns user\_id and date. I'd like to graph out DAU/MAU (daily active users / monthly active users) on a daily basis. For example:
```
Date MAU DAU DAU/MAU
2014-06-01 20,000 5,000 20%
2014-06-02 21,000 4,000 19%
2014-06-03 20,050 3,050 17%
... ... | Assuming you have values for each day, you can get the total counts using a subquery and `range between`:
```
with dau as (
select date, count(userid) as dau
from dailysessions ds
group by date
)
select date, dau,
sum(dau) over (order by date rows between -29 preceding and current row) as... | This one uses COUNT DISTINCT to get the rolling 30 days DAU/MAU:
(calculating reddit's user engagement in BigQuery - but the SQL is standard enough to be used on other databases)
```
SELECT day, dau, mau, INTEGER(100*dau/mau) daumau
FROM (
SELECT day, EXACT_COUNT_DISTINCT(author) dau, FIRST(mau) mau
FROM (
SE... | Querying DAU/MAU over time (daily) | [
"",
"sql",
"postgresql",
""
] |
I've created a query.In that query,there are some tables which are joined to another
table.I m directly getting the values of columns ContactId,FirstName,LastName,CreatedOn.
For paymnettype column,I m parsing the value inside of P.new\_name(the values are something like 'Credit Card - 2014-06-29').There are 2 type of v... | Drawing on the ideas of [my previous (and hackish) answer](https://stackoverflow.com/a/24512477/1535706) , I could devise the following (even more hackish, though more terse) solution:
```
SELECT C.ContactId,C.FirstName,C.LastName,C.CreatedOn,
CASE
WHEN (
COUNT(CASE x.payment... | I think by splitting it into two parts, you can get a fairly elegant solution. The first part deals with the PaymentType and the second does the grouping/summing based on that.
```
SELECT
ContactId
,FirstName
,LastName
,CreatedOn
,SUM(subamount) totalamount
,paymenttype
FROM
(
Select
... | SQL How To Control The Grouping Column | [
"",
"sql",
""
] |
Good morning my beloved sql wizards and sorcerers,
I am wanting to substitute on 3 columns of data across 3 tables. Currently I am using the NVL function, however that is restricted to two columns.
See below for an example:
```
SELECT ccc.case_id,
NVL (ccvl.descr, ccc.char)) char_val
F... | You could nest NVL:
```
NVL(a, NVL(b, NVL(c, d))
```
But even better, use the SQL-standard [COALESCE](http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm), which does take multiple arguments and also works on non-Oracle systems:
```
COALESCE(a, b, c, d)
``` | How about using [**COALESCE**](http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm#SQLRF00617):
```
COALESCE(ccvl.descr, ccc.char)
``` | Using NVL for multiple columns - Oracle SQL | [
"",
"sql",
"oracle",
"coalesce",
"nvl",
""
] |
Intention: detect whether a numeric sequence contains gaps. No need to identify the missing elements, just flag (true / false) the sequence if it contains gaps.
```
CREATE TABLE foo(x INTEGER);
INSERT INTO foo(x) VALUES (1), (2), (4);
```
Below is my (apparently correctly functioning) query to detect gaps:
```
WITH ... | Try this:
```
SELECT
CASE WHEN ((MAX(x)-MIN(x)+1 = COUNT(DISTINCT X)) OR
(COUNT(DISTINCT X) = 0) )
THEN 'TRUE'
ELSE 'FALSE'
END
FROM foo
```
`SQLFiddle demo` | The following should detect whether or not there are gaps:
```
select (case when max(x) - min(x) + 1 = count(distinct x)
then 'No Gaps'
else 'Some Gaps'
end)
from foo;
```
If there are no gaps or duplicates, then the number of *distinct* values of x is the max minus the min plus 1. | detect gaps in integer sequence | [
"",
"sql",
"postgresql",
""
] |
I want to get values which are not present in the table ,by considering the values only in the IN clause .
For example ,
```
select orderNumber from order where orderNumber in (List of orderNumbers)
```
This will give the orderNumbers which are present in the table by considering the values present in the IN clause ... | You need a join to do this with a `left outer join` and a `where` clause:
```
select on.*
from (select 1 as OrderNumber from dual union all
select 2 from dual
. . .
select n from dual
) ordn left outer join
orders o
on o.ordernumber = ordn.ordernumber
where o.ordernumber is NULL;
``` | I think what you are looking for is the `MINUS` keyword. This works without an `IN` clause though, but you should be able to make this work for your usecase.
This gives all ordernumbers in `in_clause_table` that are not in `order`.
```
SELECT ordernumbers FROM in_clause_table
MINUS
SELECT orderNumber FROM order;
```
... | Get values from a table which are not present only in the 'IN' clause | [
"",
"mysql",
"sql",
"oracle",
"plsql",
""
] |
This is my current select on my table:
```
SELECT count(*) as Titel, KuenstlerName FROM Bild GROUP BY KuenstlerName;
+-------+---------------+
| Titel | KuenstlerName |
+-------+---------------+
| 3 | Klee |
| 1 | Klingt |
| 1 | Marc |
| 6 | Picasso |
| 1 | van Gogh ... | Probably not the most elegant solution but this would work:
```
SELECT count(*) as Titel, KuenstlerName
FROM Bild
GROUP BY KuenstlerName
UNION ALL
SELECT count(*) as Titel, 'Total' AS KuenstlerName
FROM Bild
```
(someone jumped in with virtually the same solution while I was typing, UNION ALL should be marginally ... | Try this:
`SELECT sum(titel),coalesce(KuenstlerName,'Total')
FROM testdb.titel
GROUP BY KuenstlerName with rollup;`
Thanks.
Added screenshot of result.
 | SQL: Count column and show the total result | [
"",
"mysql",
"sql",
"select",
"count",
"sum",
""
] |
I have these tables I want to create for a Grooming Shop:
```
CREATE TABLE Pets(
Id int NOT NULL PRIMARY KEY IDENTITY
,Name varchar(20)
,Breed varchar(35)
,[Weight] decimal (10,2) NOT NULL
,Cat bit NOT NULL
,Dog bit NOT NULL
)
CREATE TABLE UserInfo(
Id int NOT NULL PRIMARY KEY IDENTITY
... | Since each user will have one or more pets and a pet presumably has only one owner, I suggest you add UserInfoId to the Pets table and remove PetId from the UserInfo table. I also suggest you remove PetId from the Appointment table and create a separate table for the pets included in the appointment. So the appointment... | No, you needn't have pets info in appointment table because the information related to pet can be retrieved from the UserInfo table itself. | sql server relationships between 3 tables | [
"",
"sql",
"sql-server",
""
] |
I have the following tables in my database
A table with users:
```
---------------------
| userId | username |
---------------------
| 1 | john doe |
| 2 | jane doe |
---------------------
```
A list of "interests"
```
---------------------
| intId | interest |
---------------------
| 1 | books |... | Something like this should do it with a `DISTINCT` if you're working with interest names:
```
SELECT DISTINCT u.UserName
FROM Users u
INNER JOIN UserInterests ui ON ui.userId = u.userId
INNER JOIN Interest i on i.intId = ui.intId
WHERE i.Interest in ('books', 'cars')
```
If you want to do it based on interest IDs:
... | ```
SELECT *,
STUFF((SELECT DISTINCT ','+u.username
FROM dbo.UserInterests ui
INNER JOIN dbo.[user] u ON u.userid = ui.UserId
WHERE ui.IntId=i.intId
FOR XML PATH('')),1,1,'')
FROM dbo.Interests i
``` | Find interests of a user and let it appear only once in the result set | [
"",
"sql",
"sql-server",
"sql-server-2008-r2",
""
] |
I need to convert datetime to ddmmyyyy as string/varchar in sql server. Let me repeat, not dd/mm/yyyy. I have searched and found only related to dd/mm/yyyy
```
Datetime VARCHAR
'02-07-2014' '02072014'
``` | `Select Replace(CONVERT(VARCHAR(20), GETDATE(), 103),'/','')`
OR
`select substring(CONVERT(VARCHAR(10),GETDATE(),103),1,2) + substring(CONVERT(VARCHAR(10),GETDATE(),103),4,2) +
substring(CONVERT(VARCHAR(10),GETDATE(),103),7,4)`
will does the same
Input: `02-07-2014`
This will give output:
`02072014` | **SQL Code:**
```
Replace(CONVERT(VARCHAR(20), GETDATE(), 103),'/','')
``` | Convert datetime to ddmmyyyy in SQL server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"datetime",
"sql-server-2008-r2",
""
] |
Hi i'm using this command to left join a table with another table that has a little more records but it keep printing NULL. I want that NULL to become 0.
```
SELECT * FROM TABLE1
Left JOIN Table2 ON TABLE1.ID=Table2.IDRel
UPDATE Table2 SET IDRel = 0 where IDRel = NULL
``` | The update should not be needed.
As you said Table2 `has a little more records` that's the key thing here, that means that for any row from Table1 for which no matching `IDRel` value could be found that column (`IDRel`) will stay `NULL`.
Now you could for example use `ISNULL(IDRel, 0)` to replace null value with 0, bu... | IS the update even needed?
```
SELECT T1.*, coalesce(t2.IDREL,0) as IDREL
FROM TABLE1 T1
Left JOIN Table2 ON TABLE1.ID=Table2.IDRel
``` | Can't update from NULL to 0 | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
"dbo",
""
] |
I have a table play day with following columns date\_played, winner, loser
with following values,
```
(Jun-03-14, USA, China)
(Jun-05-14, USA, Russia)
(Jun-06-14, France, Germany)
.
.
.
.
(Jun-09-14, USA, Russia)
```
I need to obtain all instances where USA has won exactly 3 rows in a sequence.
I tried with the foll... | You can use the following query.
```
select winner,loser,date,cnt from (select winner, loser, date, date - lag(date,3) over ( order by date) as cnt from playday) where cnt >=3
``` | first you need to find out when was the last time they lost.
second count the number of wins, greater than (>) the date of the last time they lost.
third return all rows greater than last loss, if count > 3.
sorry, don't have an SQL parser in front of me to put it in code properly.
```
Set @team_name = "USA";
select ... | SQL - Row Sequencing | [
"",
"sql",
"analytical",
""
] |
I have the following data in a table. The number of values in each row can vary and the number of rows could also vary.
The table has 1 column with csv formatted values. The values will always be numeric
```
Data
1,2
4
5,12, 10
6,7,8,9,10
15,17
```
I would like to end up with a temp table with the following
```
Dat... | Instead of function, you can achieve by this
```
;WITH tmp
AS (SELECT A.rn,split.a.value('.', 'VARCHAR(100)') AS String
FROM (SELECT Row_number() OVER(ORDER BY (SELECT NULL)) AS RN,
Cast ('<M>' + Replace([data], ',', '</M><M>') + '</M>' AS XML) AS String
FR... | First create a user defined function to convert each row of 'DATA' column to a intermediate table as:
```
/****** Object: UserDefinedFunction [dbo].[CSVToTable]******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[CSVToTable] (@InStr VARCHAR(MAX))
RETURNS @TempTab TABLE
(id int not null... | SQL Query for Min and Max Values | [
"",
"sql",
"sql-server",
""
] |
I am building a small query to find all CustomerNumbers where all of their policies are in a certain status (terminated).
Here is the query I am working on
```
select
a.cn
,p.pn
, tp = COUNT(p.pn)
, tp2 = SUM(case when p.status = 4 then 1 else 0 end)
from
(
select cn, cn2
from bc
... | You can't use aliases at the same level of a query. The reason is that the `where` clause is *logically* evaluated before the `select`, so the aliases defined in the `select` are not available in the `where`.
A typical solution is to repeat the expression (other answers) or use a subquery or cte:
```
with cte as (
... | You cannot use the aliased aggregate column names in the where clause. You have to use the expression itself instead. Also you cannot use it as where cluase, but use it in the having clause
```
HAVING COUNT(p.PolicyNumber) = SUM(case when p.status = 4 then 1 else 0 end)
``` | How do I compare SUM and COUNT()s in SQL? | [
"",
"sql",
""
] |
Hey all I have the following query:
```
SELECT LTRIM(STR(CAST(CAST('7/1/2014 9:07:00 AM' as datetime) AS float), 20, 10)) ContactDateTime
```
This query produces this number: **41819.3798611111**
Now what I am needing to do is convert that back to the normal **'7/1/2014 9:07:00 AM**' date (if thats even possible) th... | Here's a method for rounding the DateTime to the nearest second:
```
DECLARE @Float FLOAT
SET @Float = 41819.3798611111
SELECT DATEADD(ms, 500 - DATEPART(ms, CAST(@Float AS DATETIME) + '00:00:00.500'), CAST(@Float AS DATETIME))
```
`2014-07-01 09:07:00.000` | SELECT CAST(41819.3798611111 AS DATETIME) | SQL date to a float then back to a date | [
"",
"sql",
"sql-server",
"date",
"casting",
"floating-point",
""
] |
I have altered my stored procedure by mistake and I have no backup of the database. Is there any way of recovering my work ? | Try running this. It gets a list of the queries that are in the plan cache, it may be buried in there.
```
SELECT execquery.last_execution_time AS [Date Time], execsql.text AS [Script] FROM sys.dm_exec_query_stats AS execquery
CROSS APPLY sys.dm_exec_sql_text(execquery.sql_handle) AS execsql
ORDER BY execquery.last_ex... | No, there isn't. The stored procedures are part of the database.
Take this as an opportunity to learn to do backups. | Is there any way to recover a stored procedure overwritten with an ALTER statement? | [
"",
"sql",
"sql-server",
"database",
"sql-server-2008",
""
] |
I'm trying to get data from one table, so I join it like so:
```
SELECT A.ACCT_NO
FROM ACCOUNT AS A
RIGHT OUTER JOIN CUSTOMER AS C
ON A.CUST_ID = C.CUST_ID
WHERE C.FIRST_NM = 'ADAM';
```
The problem right now is that I'm somewhat confused with regards to how the joins are functioning. If I change it to:
``... | When using outer joins, the limiting criteria on the table where you only want matching records MUST be placed on the join OR you have to use an or condition to handle NULL. If you don't, you will get the same results as an INNER Join. It has to do with when the join occurs vs when the where clause criteria is applied.... | This query will return nulls for the values that are not in Account table and all the records from the Customer table
```
SELECT *
FROM ACCOUNT AS A
RIGHT OUTER JOIN CUSTOMER AS C
ON A.CUST_ID = C.CUST_ID
```
This query will return nulls for the values that are not in Customer table and all the records from ... | Inner Join, and Outer Join confusion | [
"",
"sql",
"join",
""
] |
I have the following SQL query:
```
SELECT v.PassNo, VName, e.eName, d.dtName, v.EntryTime
FROM Visitorlogo_tbl v
LEFT JOIN EmployeeMaster_tbl e ON v.empid=e.eId
JOIN DepartmentMaster_tbl d ON v.Deptid=d.dtId
WHERE v.EntryTime >= '2014-06-29'
```
And I'm getting the following output:
```
P... | Concatenating strings, where one of your strings are `NULL` will always yield `NULL`.
For example: `SELECT NULL + 'Moo'` will result in `NULL` - always.
`ISNULL()` accepts 2 arguments and will return the second when the first resolves to `NULL` - [BOL](http://msdn.microsoft.com/en-us/library/ms184325.aspx)
Do you mean... | If you concatenate null with anything, it will return null. So you need to check for null to get the proper result. You can use the following query instead
```
select v.PassNo as 'Badge Id',VName as VisitorName,ISNULL(e.eName,'') + ISNULL(' ('+ d.dtName+')','') as 'Name(Department)',v.EntryTime from Visitorlogo_tbl v
... | While concatenating two columns an output mismatch occurs | [
"",
"sql",
"sql-server",
""
] |
I'm trying to write an SQL Server query to extract rows with the highest 'Revision' number for each distinct ColumnId.
For example if I have a data set such as:
```
Id ColumnId Revision
------------------------
1 1 1
2 1 2
3 1 3
4 2 1
5 2 2
6 ... | You could use a subquery and then inner join back on the ColumnId and the MaxRevision like this:
```
SELECT A.Id, A.ColumnId, A.Revision
from Bug A
INNER JOIN
(SELECT ColumnId, MAX(Revision) As MaxRevision
FROM BUG
GROUP BY ColumnId ) B ON
A.ColumnId = B.ColumnId AND
A.Revision = B.MaxRevision
``` | You can use `ROW_NUMBER`, for example with a common-table-expression(CTE):
```
WITH CTE AS
(
SELECT Id, ColumnId, Revision,
RN = ROW_NUMBER() OVER (PARTITION BY ColumnId ORDER BY Revision DESC)
FROM Bug
)
SELECT Id, ColumnId, Revision
FROM CTE
WHERE RN = 1
```
`Demo` | SQL Query group by highest revision number | [
"",
"sql",
"sql-server",
""
] |
I have a #temptable which I'm trying to populate but its not working.
```
DECLARE
@nBranchId int
,@tmStartDate datetime
,@tmEndDate datetime
SELECT @nBranchId = 3483
,@tmStartDate = DATEADD(DAY, -10, GETDATE())
,@tmEndDate = GETDATE()
CREATE table #temptable (
nRes... | You have different length data types
To avoid this problem use a [`SELECT INTO`](http://www.w3schools.com/sql/sql_select_into.asp) statement
`#Temptable` would be created automatically with correct data type (Extra benefit you don't have to script `CREATE` statement)
```
DECLARE
@nBranchId int
,@tm... | Should be fixed by changing these two columns to look like this. Likely what is going on is, you are trying to insert varchars greater than 50 characters into a varchar(50) column.
```
strPaperId varchar(max),
strPosName varchar(max)
``` | Getting error when inserting into temptable | [
"",
"sql",
"t-sql",
""
] |
Besides from Import and Export Wizard, Is there any query to transfer a table from a server to another server in SQL Server 2008?
```
SELECT * INTO [Server1].[db_name].[dbo].[table_name]
FROM [Server2].[db_name].[dbo].[table_name]
``` | There are several options. If you have the correct permissions, you can create a Linked Server following instructions here: <http://msdn.microsoft.com/en-us/library/ff772782.aspx>
and then use OPENQUERY (<http://msdn.microsoft.com/en-us/library/ms188427.aspx>) to select the records:
```
SELECT * INTO new_db.new_schem... | Assuming both server1 and server2 are sql server then You do not need a openquery. Create a linked server on server1 for server2 and write query
select \* into server1.schema.table\_name
from server2.schema.table\_name | Transfer a table from a server to another server | [
"",
"sql",
"sql-server",
"sql-server-2008",
"t-sql",
""
] |
I have a select that brings me some primary keys. I need to SELECT all values from other table that are not listed in the previous query. How can I do it?
I have been trying:
```
SELECT id
FROM tab1,
,(SELECT id...
WHERE LIKE '%abc%'
) AS result
WHERE result != tab1.id;
```
But didn't work, it brings me ... | You can try this,
SELECT \* from table1 WHERE id NOT IN (SELECT id from table2 where );
where "id" will be common coloumn in both tables i.e in table1 and table2.
and will be the condition on whatever basis you need to fetch records from table2 in inner query. | ```
SELECT tab1.id
FROM tab1 LEFT OUTER JOIN
(SELECT id
FROM ...
WHERE LIKE '%abc%'
) AS result
ON result.ID = tab1.id
where result.ID is null;
``` | SELECT values excluding values from other SELECT | [
"",
"sql",
"postgresql",
""
] |
I have a table `node_weather` that looks like this:
```
+--------------------+--------------+------+-----+--------------------+
| Field | Type | Null | Key | |
+--------------------+--------------+------+-----+--------------------+
| W_id | mediumint(9) | NO | PR... | Maybe something like this:
```
SELECT
*
FROM
node_weather
JOIN
(
SELECT
tblInner.P_id,
MAX(tblInner.time) AS maxTime
FROM
node_weather as tblInner
GROUP BY
tblInner.P_id
) AS tblMax
ON tblMax.maxTime = node_weather.time
AND tblMax.P_id = node_weather.P_id
`... | Try this query. It is faster than sub query..
```
select nw1.* from node_weather nw1
LEFT JOIN node_weather nw2 on nw2.P_id = nw1.P_id and nw2.time>nw1.time
where nw2.W_ID is null;
``` | MySQL - how to retrieve the last recorded values grouped by one of the fields? | [
"",
"mysql",
"sql",
""
] |
I have a `order` table and each order in that table belongs to either a `device` or `part` (these two have no specific intersection in fields).
So I need to store the `did` or `pid` as FK in `order` table.
```
"device"
+----+....
| id |<---------+
+----+.... :
: : : : . :
:
... | Either use **exclusive foreign keys** or **inheritance**, as explained [here](https://stackoverflow.com/a/13317463/533120). Just be careful about CHECK, which is [not enforced](https://stackoverflow.com/a/2115641/533120) by MySQL, so you'll have to "emulate" it via trigger.
Please don't do the "type" approach, it can ... | I would go with two tables, one for the order and the other for item. Item table will have ID, type (part or device; P or D) and the rest of the details. In the order table, I will just have a FK to the Item Table ID. | Foreign Key From two tables in one column in SQL | [
"",
"mysql",
"sql",
"database-design",
"relational-database",
"foreign-key-relationship",
""
] |
I would like to return table entries from an inner join which do not have any matching entries in the second column.
Lets consider the following two tables:
Table one:
```
Name Number
A 1
A 2
A 4
```
Table two:
```
Name ID
A 3
```
The query should return Name=A ID=3... | ```
SELECT *
FROM Table2
WHERE NOT EXISTS (
SELECT *
FROM Table1
WHERE Table1.Name = Table2.Name AND Table1.Number = Table2.ID
)
``` | Yes, instead of using an INNER join, use a LEFT or a FULL OUTER join. This will allow null values from the other table to appear when you have a value in one of your tables.
The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2).
The LEFT JOIN keyword returns all r... | SQL Inner Join and further requirements | [
"",
"sql",
"join",
"where-clause",
""
] |
The architecture of my DB involves records in a Tags table. Each record in the `Tags` table has a string which is a `Name` and a foreign kery to the `PrimaryID's` of records in another `Worker` table.
Records in the Worker table have tags. Every time we create a Tag for a worker, we add a new row in the Tags table wit... | This is a variant of relational division. Here's one attempt:
```
select workerid
from tags
where name in ('foo', 'bar')
group by workerid
having count(distinct name) = 2
``` | You can use the following:
```
select WorkerID
from tags where name in ('foo', 'bar')
group by WorkerID
having count(*) = 2
```
and this will retrieve your desired result/
Regards. | Multiple records in a table matched with a column | [
"",
"sql",
"sql-server",
"database",
"procedures",
""
] |
I have used following query for getting info which is greater than 2012 but I am not getting correct data with compare to date ,please give me correct query?
MYSQL QUERY:
```
SELECT a.invoiceno,
a.invoicerefno,
a.invoicedate,
c.companyname,
a.grandtotal,
a.twempname,
itemdescr... | Try this:
```
SELECT a.invoiceno,
a.invoicerefno,
a.invoicedate,
c.companyname,
a.grandtotal,
a.twempname,
itemdescription,
quantity
FROM twsql_twalldata.t_invoicedet a
INNER JOIN twsql_twalldata.t_salesinv_items b ON a.invoiceno=b.invoiceno
INNER JOIN twsql_twalldata.t... | If the `invoicedate` data type is datetime then you will need one correction i.e. using proper parentheses for the OR condition.
```
WHERE
a.twempname NOT LIKE '%Auto%'
AND ( itemdescription LIKE '%AMC%' OR itemdescription LIKE '%annual maintenance contract%')
AND invoicecancelled=0
AND a.invoicedate > '2012-04-01 00... | mysql query with date comparison | [
"",
"mysql",
"sql",
"date",
"select",
""
] |
I need to find active records that fall between a range of date parameters from a table containing applications. First, I look for a record between the date range in a table called 'app\_notes' and check if is linked to an application. If there is no app\_note record in the date range, I must look at the most recent ap... | ```
SELECT *
FROM individual i
INNER JOIN app_indiv ai
ON ai.indiv_id = i.indiv_id
OUTER APPLY
(
SELECT TOP 1 * FROM app_note an
WHERE an.app_indiv_id = ai.app_indiv_id
AND an.when_mod < @date_to
ORDER BY an.when_mod DESC
) d
WHERE d.status = 'active'
```
Find the last note less than end date,... | (untested) You'll need to use a [CASE](http://www.dotnet-tricks.com/Tutorial/sqlserver/1MS1120313-Understanding-Case-Expression-in-SQL-Server-with-Example.html) switch.
```
SELECT DISTINCT individual.indiv_id
FROM individual INNER JOIN
app_indiv ON app_indiv.indiv_id = individual.indiv_id INNER JOIN
app_note ON app_i... | Query for active records between date range or most recent before date range | [
"",
"sql",
"sql-server",
""
] |
I have a SQL Server table like this:
`table(Id, DestId, WeekDay)`
WeekDay is nvarchar holding values like `Monday`, `Tuesday`, `Wednesday`, etc. Here `Id` and `Weekday` are composite primary keys. I want the result of select query to be sorted on `WeekDay` order, i.e. Monday should come before Tuesday and Wednesday an... | Solution here: <http://dbaspot.com/sqlserver-faq/393109-order-day-week.html>
You have to make a case structure in your SQL statement like this one:
```
select *
from table
ORDER BY case WeekDay when 'Monday' then 1
when 'Tuesday' then 2
when 'Wednesday' then 3
when 'Thursday' then 4
when 'Friday' then... | You can try this:
```
SELECT * FROM Table ORDER BY CHARINDEX(LEFT(WeekDay,3),'MonTueWedThuFriSatSun')
```
`CHARINDEX(LEFT(WeekDay,3),'MonTueWedThuFriSatSun')` will return the index position. If you want to **sort from Sunday**, the you can change the string to `'SunMonTueWedThuFriSat'` | Sort table data on weekday | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
i'm trying to find the sum of 2 count values stated in the query below. Even though the query is working fine when I'm just finding out the count values, when i try to find the sum of the count values i get an error...Please Help..
```
SELECT COUNT(BUG_ID) BUG_COUNT,
COUNT(STATUS) CLOSED_COUNT,
(BUG_COUNT + CLOSED_COU... | Try like this
```
SELECT COUNT(BUG_ID) BUG_COUNT,COUNT(STATUS) CLOSED_COUNT,
(COUNT(BUG_ID) + COUNT(STATUS)) AS TOTAL_COUNT
FROM bugzilla_dashboard
WHERE CATEGORY='Legacy';
```
*Or:*
```
SELECT BUG_COUNT,CLOSED_COUNT,(BUG_COUNT + CLOSED_COUNT) AS TOTAL_COUNT
FROM
(
SELECT COUNT(BUG_ID) BUG_COUNT,
... | ```
SELECT COUNT(BUG_ID) BUG_COUNT,
COUNT(STATUS) CLOSED_COUNT,
(COUNT(BUG_ID) + COUNT(STATUS)) AS TOTAL_COUNT
FROM bugzilla_dashboard WHERE CATEGORY='Legacy';
```
obviously... | Find sum of multiple sql counts | [
"",
"sql",
"aggregate-functions",
"jdeveloper",
""
] |
How to compare only day and month with date field in mysql?
For example, I've a date in one table: `2014-07-10`
Similarly, another date `2000-07-10` in another table.
I want to compare only day and month is equal on date field.
I tried this format. But I can't get the answer
```
select *
from table
where STR_TO_DATE... | Use DATE\_FORMAT instead:
```
SELECT DATE_FORMAT('2000-07-10','%m-%d')
```
yields
```
07-10
```
Here's your query re-written with `DATE_FORMAT()`:
```
SELECT *
FROM table
WHERE DATE_FORMAT(field, '%m-%d') = DATE_FORMAT('2000-07-10', '%m-%d')
AND id = "1"
``` | you can do it with the `DAYOFMONTH` and `MONTH` function:
```
SELECT *
FROM table
WHERE DAYOFMONTH(field) = 31 AND MONTH(field) = 12 AND id = 1;
```
**EDIT:**
Of course you can write following too if you want to compare two fields:
```
SELECT *
FROM table
WHERE
DAYOFMONTH(field) = DAYOFMONTH(field2)
AND MO... | Compare only day and month with date field in mysql | [
"",
"mysql",
"sql",
"date",
"select",
""
] |
I´m trying to add up the amounts from a table if the customer id (KUNDENID) is the same.
These are my two tables:
```
+----------+------------+--------+
| KUNDENID | datum | Betrag |
+----------+------------+--------+
| 2 | 2013-06-05 | 120.5 |
| 1 | 2013-02-05 | 20.95 |
| 3 | 2013-02-05 |... | Use `LEFT JOIN` instead of `INNER JOIN`.
```
SELECT k.KUNDENID, vorname, nachname, IFNULL(SUM(Betrag), 0) AS gesamt
FROM kunde k
LEFT JOIN verkauf v ON k.KUNDENID = v.KUNDENID
GROUP BY k.KUNDENID;
```
Here's [Wikipedia](http://en.wikipedia.org/wiki/Join_%28SQL%29#Left_outer_join)'s basic explanation. They... | Yes you can use Left outer join in place of Inner Join Like :
```
SELECT k.KUNDENID, vorname, nachname, SUM(Betrag) AS Betrag
FROM kunde k LEFT OUTER JOIN verkauf v
ON k.KUNDENID = v.KUNDENID GROUP BY k.KUNDENID;
``` | INNER JOIN: add up amounts with same id | [
"",
"mysql",
"sql",
"join",
"inner-join",
""
] |
I have two tables, Alpha & Bravo. Bravo has a column `id` (integer, primary key) and some other columns that are not relevant for this question. Alpha has columns `id` (integer, primary key), `bravo_id` (foreign key to table Bravo), `special` (a single char, null for most rows but has a value for certain important rows... | This works in both SQL Server & Oracle:
```
select A.id, A.bravo_id, A.created, B.id, B.created
from Alpha A
left join Alpha B on A.bravo_id = B.bravo_id
and B.created < A.created
and B.special is null
where A.special is not null
and (B.created is null or
B.created = (select ... | ```
SELECT a.Id, a.Bravo_Id, a.Created, d.Id, d.Created FROM @Alpha a
OUTER APPLY
(
SELECT TOP 1 da.id, da.Created
FROM @Alpha da
WHERE da.Special IS NULL
AND da.Bravo_Id = a.Bravo_Id
AND da.Created < a.Created
ORDER BY da.Created DESC
) d
WHERE a.Special IS NOT NULL
```
You can bind b... | How can I get certain rows and the "previous" rows from a table that includes a datetime column? | [
"",
"sql",
"sql-server",
"oracle",
"query-optimization",
""
] |
I have following table in my SQL Database and need to group it by the max-value of an 5 minute period of time.
```
+------+--------+------------------+
| Path | Sample | DateTime |
+------+--------+------------------+
| Srv1 | 0.5 | 2014-07-04 10:48 |
| Srv1 | 0.7 | 2014-07-04 10:50 |
| Srv1 | 0.9 | 2... | You are putting `pd.DateTime` in the selected columns AND the group by clause, so you're not actually performing any aggregation.
There are many ways to do this, some better than others depending on your data, but try this :
```
SELECT TOP (100) PERCENT
me.Path,
MAX(pd.SampleValue) AS Sample,
DATEADD(M... | Try this
```
SELECT Path, MAX(Sample), DATEADD(MINUTE, (CASE WHEN DATEPART(MINUTE, Created)%5 BETWEEN 1 AND 2 THEN 0 ELSE 5 END)-(DATEPART(MINUTE, Created))%5, Created) AS NewDate
FROM ...
GROUP BY Path, DATEADD(MINUTE, (CASE WHEN DATEPART(MINUTE, Created)%5 BETWEEN 1 AND 2 THEN 0 ELSE 5 END)-(DATEPART(MINUTE... | SQL Group by time | [
"",
"sql",
"sql-server",
"group-by",
""
] |
I want my query to return the rows of the table where a column contains a specific value first
so i given query like this:
```
SELECT IDName
FROM Type_ofID_tbl
WHERE deleted = 0
ORDER BY(IDName ='Emirates ID'), IDName
```
but this showing error
Incorrect syntax near '='. | Try this
```
select IDName
from Type_ofID_tbl
where deleted=0 order by case when IDName ='Emirates ID' then 1 else 2 end
``` | There is no need for `(IDName ='Emirates ID')` in the `ORDER BY` clause; it should be like this
```
SELECT IDName
FROM Type_ofID_tbl
WHERE deleted = 0
ORDER BY IDName ASC
```
If you want to order columns who has the `IDName ='Emirates ID'`
```
SELECT IDName
FROM Type_ofID_tbl
WHERE deleted = 0
AND ... | while return rows with a specific value first getting syntax error | [
"",
"sql",
"sql-server",
""
] |
I have a table called `course offerings`. In this table you will find each course with its respective `course_start_date` and `course_end_date`. I am also using an enum field called `course_status`. There are two possible status for each course `IN SESSION` or `Closed` but not both. How could I create a query that will... | I don't know if there is a dynamic way to do what you are trying.
This simple SQL query can help you update such records:
```
UPDATE course_offerings
SET course_status = 'Closed'
WHERE course_end_date < SYSDATE
``` | Try this
```
UPDATE course_offerings
SET course_status = 'Closed'
WHERE course_end_date = "passed_date";
``` | Expiring a value based on a date field | [
"",
"mysql",
"sql",
""
] |
I'm struggling to even explain what I need to do so please be patient with me.
I have the following table and rows in it:
TBNAME: **`Distances`**
# Track, Person, Date, Distance
```
TRACK1, P1, 1/1/2014, 15
TRACK2, P1, 13/1/2014, 12
TRACK1, P1, 20/2/2014, 10
TRACK2, P1, 15/1/2014, 9
TRACK1, P2, 2/1/2014, 11
TRACK2, ... | Try this:
```
SELECT T1.Person, T1.Track, MAX(T1.Date), MIN(T1.Distance),
T2.Track, MAX(T2.Date), MIN(T2.Distance)
FROM Distances AS T1 INNER JOIN
Distances AS T2 ON T1.Person = T2.Person
WHERE T1.Track <> T2.Track AND T1.Track = 'Track1'
GROUP BY T1.Track, T1.Person, T2.Track
```
Th... | Look for [`ROW_NUMBER()`](http://technet.microsoft.com/library/ms186734%28v=sql.110%29.aspx) and [`OVER PARITION BY`](http://technet.microsoft.com/library/ms189461%28v=sql.110%29.aspx).
Idea is something like (I did not try to run this query):
```
;WITH
data AS
(
SELECT
*,
-- returns number for ea... | Select values from multiple rows from 1 table as 1 record | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
I have created a View:
```
CREATE VIEW Lunch
AS
SELECT 'Beer' AS item
UNION SELECT 'Olives'
UNION SELECT 'Bread'
UNION SELECT 'Salami'
UNION SELECT 'Calamari'
UNION SELECT 'Coffee';
GO
```
Then I executed the following query in a different query.
```
SELECT item FROM Lunch
```
This is resulting in the ... | It doesn't actually hold data, but it can evaluate SQL, which is all you're doing in the definition.
So the following can be evaluated:
```
SELECT 'Beer' AS item
UNION SELECT 'Olives'
UNION SELECT 'Bread'
UNION SELECT 'Salami'
UNION SELECT 'Calamari'
UNION SELECT 'Coffee';
```
The same as a view defined wi... | I don't fully understand the question. The view is not "holding data", it is holding a query. The query statement has constants in it that are turned into a result set that can be used by other queries.
You can think of a query as substituting the text of the query directly into a statement. So, when you do:
```
sele... | Can a View hold some data | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
If I have names of locations along with location id's in the same table, how can I display the location name based on the location id? The location id will never change, but the name might, so by using the value of the id instead of the name will keep all records available. However, I want the name to be shown and not ... | Loc\_ID is presumably an integer, and Loc\_Name is presumably VarChar. Those 2 fields will never equal, so asking for a dataset where they equal each other will not give you any output.
Instead, you want something like:
```
SELECT
loc_name
FROM location
WHERE loc_id = YourLocID
```
Where YourLocID above is the... | You need to specifiy the ID you want to see the location for, i.e.:
```
select loc_name from location where loc_id = 3;
``` | Show name based on ID | [
"",
"sql",
"select",
"where-clause",
""
] |
```
DECLARE @Chat varchar(100) = 'GiveSilk:[Axmeed] Amount:[10]'
,@TargetCharName varchar(32),@Amount int
SET @TargetCharName = (REPLACE(@Chat,'GiveSilk:[',''))
select @TargetCharName
```
thats my sql query i want to select 'Axmeed' at the result but the problem is that 'Axmeed' string is not static it becomes any ... | ```
DECLARE @Chat varchar(100) = 'GiveSilk:[Axmeed] Amount:[10]'
SELECT SUBSTRING(@Chat,CHARINDEX('[',@Chat)+1,CHARINDEX(']',@Chat)-CHARINDEX('[',@Chat)-1)
``` | One option is to use Regular Expressions. A CaptureGroup is what you are looking for. For example:
```
SELECT SQL#.RegEx_CaptureGroup(
N'GiveSilk:[Axmeed] Amount:[10]', -- input string
N'GiveSilk:\[(\w+)\]', -- Regular Expression
... | SQL Query string replace | [
"",
"sql",
"sql-server",
"string",
"t-sql",
""
] |
I have data in my sql database and need to create changeControl value.
```
data changeControl
M-0101 0
M-0101 0
M-02 1
M-03 0
OT-014 1
OT-014 1
M-228 0
M-228 0
```
Are there any way to create this changeControl value depend on data? | There is an easy way, but it depend on your DB.
In SQL Server and in Oracle you can use DENSE\_RANK() to get the order of the values, using that you'll have the same number for equal values
In SQL Server
```
SELECT data
, (DENSE_RANK() OVER (ORDER BY data) - 1) % 2 changeControl
FROM Table1
```
In Oracle the... | You need to first break your data into groups, and assign each group a number.
Then join this information with main table, sort by data, and take modulo by two from group number - this will be your changeControl column.
```
select tn.*, t.RN % 2 as changeControl from tableName tn
left join
(select ROW_NUMBER() OVER (... | Creating alternating 0 and 1 values based on changing data value | [
"",
"sql",
""
] |
SQL newbie hear tearing my hair out trying to work this one out! I have a problem that is similar to this.
I have the following data and all fields are defined as CHARACTER - No DATE or TIME unfortunately thanks to poor design by the original DBA
```
Surname Name LoginDate LoginTime
Smith John 2014... | Try this Query -
```
With MaxTimeStamp as
(
SELECT Surname, Name, Max(TIMESTAMP(LoginDate, LoginTime)) as LoginDateTime
FROM YourTable
group by Surname, Name
)
select c.Surname, c.Name, d.LoginDate, d.LoginTime,
from MaxTimeStamp c
Join YourTable d
on c.Surname = d.Surname
and c.Name = d.... | I have split it into two parts, to find the newest login per user and do the group by. I then join to the data again to find the record.
```
select
dt.Surname
, dt.Name
, dt.LoginDate
, dt.LoginTime
from
dataTable dt
join
(select Surname, Name, MAX(LoginDate+LoginTime) ts from #temp... | SQL To Find Most RECENT row Using GROUP BY | [
"",
"sql",
""
] |
I'm writing an application that implements a message system through a 'memos' table in a database. The table has several fields that look like this:
```
id, date_sent, subject, senderid, recipients,message, status
```
When someone sends a new memo, it will be entered into the memos table. A memo can be sent to multip... | I think you would be better off having your recipients as a child table of the memos table. So your memo's table has a memo ID which is referenced by the child table as
```
MemoRecipients
-----
MemoRecipientId INT PRIMARY KEY, IDENTITY,
MemoId INT FK to memos NOT NULL
UserId INT NOT NULL
```
for querying specific mem... | I am not sure how your application is exactly pulling these messages, but I imagine that better way would be creating a table `message_recepient`, which will represent many-to-many relationship between recipients and memos
```
id, memoId, recepientId
```
Then your application could pull messages like this
```
SELECT... | How to tightly contain an SQL query result | [
"",
"sql",
""
] |
I have a `varchar` which is coming through as the following format: `yyyy-dd-MM hh:mm:ss`
I need to be able to convert that to a valid `datetime`, what will be the best method?
**Edit for example:**
```
DECLARE @d varchar = '2014-17-01 12:00:00'
SELECT CONVERT(DATETIME, @d, 103);
```
returns
```
Msg 241, Level 16... | Via `CONVERT`?
```
SELECT CONVERT(DATETIME, '2014-31-01 17:00:00', 103 /* British */);
(No column name)
2014-01-31 17:00:00.000
``` | EDITED to add SET DATEFORMAT. This resolved the error for me and ensures everything gets into the correct bucket.
```
SET DATEFORMAT ydm
DECLARE @d VARCHAR(20) = '2014-17-01 12:00:00';
DECLARE @targetDate DATETIME = GETDATE(); -- Control Date
DECLARE @passedDate DATETIME = CAST(@d AS DATETIME);
SELECT @targetDate, @... | SQL Custom datetime format to datetime | [
"",
"sql",
"sql-server",
"converters",
""
] |
I have a table:
```
[letter] [Name] [status] [price]
A row1 1 11
A row1 1 15
B row2 2 9
B row2 3 23
B row2 3 30
```
And want to select data something like this:
```
SELECT letter, Name,
COUNT(*),
... | Close. Probably want this instead:
```
SELECT letter, Name,
COUNT(*),
SUM(CASE WHEN price>10 THEN 1 ELSE 0 END)
FROM TableThatShouldHaveAppearedInTheQuestionInTheFromClause
GROUP BY letter, Name
```
should work. Assuming that the intention of the fourth column is to return the count of the number of rows, within... | Since nulls are not used in aggregate functions:
```
SELECT letter
, name
, count(*)
, count(
case when price > 10 then 1
end
)
FROM t
GROUP BY letter, name
```
You were very close. | One column condition in sql | [
"",
"sql",
"aggregate-functions",
""
] |
I need to make the results of CONCAT(ROUND(oi.OutboundUnits/oi.OutboundCalls \*100),'%') AS OutboundConv return in a 2 digit format even if the result is 9 or below. | You can use the LPAD function, with a different condition for 100% using the CASE statement, as below:
```
CASE
WHEN ROUND(oi.OutboundUnits/oi.OutboundCalls *100) = 100 THEN '100%'
ELSE LPAD(CONCAT(ROUND(oi.OutboundUnits/oi.OutboundCalls *100),'%'), 3, '0')
END
```
**Reference**:
[LPAD on MySQL Reference Man... | You can use concat and right function.
```
right(concat('0', OutboundConv), 3)
``` | Return 2 digit computation even if result is 1 digit MYSQL | [
"",
"mysql",
"sql",
""
] |
I have this query:
```
if OBJECT_ID('tempdb..#tempA') is not null drop table #tempA
create table #tempA
(
tempid varchar(5),
tempdate smalldatetime
)
declare @loopdate smalldatetime
set @loopdate = '4/2/2013'
while (@loopdate <= '4/28/2013')
begin
--Purpose is to get IDs not in TableB for each date peri... | Still a loop but maybe a little more efficient
```
while (@loopdate <= '4/28/2013')
begin
--Purpose is to get IDs not in TableB for each date period
insert into #tempA (tempid, tempdate)
select storeid, @loopdate
from
(
select tableAid
from tableA
left join tableB
... | it depends on whether not tableA has a date on it, if not then:
```
WITH DateList(DateDay) AS
(
SELECT CAST('2013-04-28' AS DATETIME)
UNION ALL
SELECT DATEADD(DAY, DATEDIFF(DAY,0,DATEADD(DAY, -1, DateDay)),0)
FROM DateList
WHERE DateDay between '2013-04-03' and '2013-04-28'
)
SELECT D... | Can this while be converted to a set based query? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2012",
""
] |
So I have this "table" which is a result of the query
```
SELECT Valoare
FROM GEConfig
WHERE Cimp IN('Societate','Adresa','Banca','CapitalSocial','Cont','CUI','NrRegCom','ModulReceptiiExtCotaTVA')
```
GeConfig is a table what is used to configurate the aplication for each client so the data that will result from ... | A more general approach is to add a row number and use it as anchor
```
WITH _ID AS (
SELECT Valoare
, _ID = Row_Number() OVER (ORDER BY Valoare)
FROM GEConfig
)
SELECT [1] = MAX(CASE WHEN _ID = 1 THEN Valoare ELSE NULL END)
, [2] = MAX(CASE WHEN _ID = 2 THEN Valoare ELSE NULL END)
, [3] = MAX(C... | Try this:
```
SELECT * from
(SELECT cast([name] AS nvarchar(MAX)) [name], row_number() over(
ORDER BY name) AS id
FROM TEMP)a pivot ( max([name])
FOR id IN ([1], [2], [3], [4], [5]) )pvt
``` | SQL PIVOT one column only | [
"",
"sql",
"sql-server",
"pivot",
""
] |
Table example:
```
time a b c
-------------
12:00 1 0 1
12:00 2 3 1
13:00 3 2 1
13:00 3 3 3
14:00 1 1 1
```
How can I get `AVG(a)` from row `WHERE b!=0` and `AVG(c)` grouped by time. Is it possible to solve with `sql` only? I mean that query should not count 1st row to get `AVG(a)`, but not the same... | You can utilize `CASE` statements to get conditional aggregates:
```
SELECT AVG(CASE WHEN b != 0 THEN a END)
,AVG(c)
FROM YourTable
GROUP BY time
```
Demo: [SQL Fiddle](http://sqlfiddle.com/#!15/612f6/8/0)
This works because a value not captured by `WHEN` criteria in a `CASE` statement will default to `NULL`, ... | ```
SELECT AVG(a), AVG(c) from table WHERE b != 0
group by time
```
Yea... is this what you need? | Very special kind of AVG statement | [
"",
"sql",
"postgresql",
""
] |
I got two table, one is member another is member\_status table. I need to get the count of the number of member in the same status.
member
```
+----+-------------+-----------+---------+--------+--------+--------------+---------+---------------------+---------------------+
| id | full_name | mobile_no | address | st... | Try
`select * from member right join member_status on (member.status = member_status.id)`
and you'll see NULL-s for member fields.
That's why you are getting more counts then you want.
One of the solutions:
`select member_status.name, count(member.id) as totalNum
from member right join member_status on (member.s... | `SELECT S.NAME, SUM(CASE WHEN S.ID = T.STATUS THEN 1 ELSE 0 END )
FROM member_status S, member T
GROUP BY S.NAME` | get all record with number of one to many table count | [
"",
"sql",
""
] |
I have this error from SSIS when i'm trying to import an access 2013 database to a sql server 2014 database
I used `Microsoft Office 15.0 Access Database Engine OLE DB Provider` For the Source
and `SQL Server Native Client 11.0` For the Destination
## TITLE: SQL Server Import and Export Wizard
Could not connect s... | The error indicates that it is not able to find the Amounts table in your Access file. Ensure that the table is present and that you have not specified any extra spaces in the table name.
Looking at the versions of SQL Server and Access you are using I have a feeling it might have to do with the drivers. Can you make ... | There is import wizard bug, when you select 'copy data from one or more table...', the automatic generated sql have single quote on table name, which cause error message, [Opening a rowset for "Amounts" failed. Check that the object exists in the database.] Click the 'preview' button(next to 'edit mapping' button), you... | SSIS error on access import | [
"",
"sql",
"sql-server",
"ms-access",
"ssis",
""
] |
I am trying to do a trigger, that select values into some tables, and then insert them into another table.
So, for now I got this. There is a lot of columns, so I don't copy them, it is only varchar2 values, and this part works, so I don't think it is useful :
```
create or replace
TRIGGER TRIGGER_FICHE
AFTER IN... | Because you're inserting into a remove table via a database link, you have [a distributed transaction](http://docs.oracle.com/cd/E29505_01/server.1111/e25789/transact.htm#CHDJCBCF):
> ... distributed transaction processing is more complicated because the database must coordinate the committing or rolling back of the c... | I am not able to understand you requirement clearly. For updating records in main table and insert the old records in audit table. we can use the below query as a trigger.(MS-SQL)
```
Create trigger trg_update ON T_AGENT
AFTER UPDATE AS
BEGIN
UPDATE Tab1
SET COL1 = I.COL1, COL2=I.COL2
FROM INSERTED I INNER JOIN Tab1... | Trigger that insert into a dblink table | [
"",
"sql",
"triggers",
"oracle10g",
""
] |
here is my Table1:
```
a b c
100 110 1
200 0 2
300 150 3
100 0 2
200 300 2
300 106 3
```
i want to show the result as that:
```
abc xyz
2 P
2 U
2 PL
```
this is because
count row where (b > a) as P and (b = '0') as U and (b <= a and b != '0') as PL.
problem is that how to show these value like P,U,PL... | You can union the results together.
```
SELECT COUNT(1) AS abc ,'P' AS xyz
FROM #temp
WHERE a > b
AND b != 0
UNION
SELECT COUNT(1) AS abc, 'U' AS xyz
FROM #temp
WHERE b = 0
UNION
SELECT COUNT(1) AS abc, 'PL' AS xyz
FROM #temp
WHERE b<= a
AND b != 0
```
I had to ad b != 0 into your P condition to match your expected r... | Use a case statement
```
SELECT Count(*) as abc, CASE WHEN b= 0 THEN 'U'
WHEN b>a THEN 'P'
ELSE 'PL' END as xyz
FROM [Table 1]
GROUP BY
CASE WHEN a>b THEN 'P'
WHEN b=0 THEN 'U'
ELSE 'PL' END
``` | sql server query count data | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
We have two tables table1 and table2
Table 1

Table 2

**We need the resultant table as :**

**All this should be done in a sin... | I think you can make it without the second query, I tested it and returned your expected values.
```
select table_2.id_pro,
product_name,
SUM(1) as Quantity,
priceprod,
SUM(1) * priceprod as 'quantity * priceprod'
from Table_2
inner join Table_1 t1 on table_2.i... | I believe this should be what you need, or fairly close anyway! You need to group up your results from your first table to get your quantity value and then join those results to your second table to be able to create your desired output.
```
SELECT t1.id_pro,
t2.product_name,
s.Quantity,
... | Join two tables and retrieve relevant data and calculate the result | [
"",
"sql",
""
] |
I have the following database:
```
paperid | authorid | name
---------+----------+---------------
1889374 | 897449 | D. N. Page
1889374 | 1795881 | C. N. Pope
1889374 | 1952069 | S. W. Hawking
```
I would like to create a table having following columns:
* paperid
* author name - for each author of this paper... | This can be **surprisingly simple** with [`array_agg()`](http://www.postgresql.org/docs/current/interactive/functions-aggregate.html) as window aggregate function combined with [`array_remove()`](http://www.postgresql.org/docs/current/interactive/functions-array.html#ARRAY-FUNCTIONS-TABLE) (introduced with pg 9.3):
``... | Here is a way to approach this problem:
Generate the list of all co-authors as a subquery. Generate the list of all authors. Then join these together and do the string manipulation to get what you want.
---
The authors is easy:
```
select paperid, npa.name as author
from newpaperauthor npa;
```
The co-authors is e... | How to eliminate cartesian product with joins while using subquery? | [
"",
"sql",
"postgresql",
"join",
"postgresql-9.3",
"cartesian-product",
""
] |
I have seen many similar questions but none that meet my needs exactly, and I cannot seem to deduce a solution on my own from inspecting the other questions.
I have the following (mock) table below. My actual table has many more columns.
```
TableA:
ID | color | feel | size | alive | age
-----------------------... | There are a variety of ways to do this. If you have a more recent version of Sybase, you can use `row_number()`:
```
select t.*
from (select t.*, row_number() over (partition by id order by id) as seqnum
from table t
) t
where seqnum = 1;
``` | Your solution with MIN has some drawbacks. It doesn't return you a specific row but MIN values from the group of rows. You can get as result rows which are not in database. Is it OK for you ?
Row\_number is supported in sybase 15.2
<http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc38151.1520... | Sybase select distinct on one column, do not care about others | [
"",
"sql",
"distinct",
"aggregate-functions",
"sybase",
""
] |
Query
```
SELECT *
from Table_2
WHERE name like ('Joe');
```
Output
```
1 100 Joe
2 200 JOE
3 300 jOE
4 400 joe
```
Why is it not case sensitive? | Problem:
> Query not case sensitive
Cause: Column 'Name' has a case-insensitive (`CI`) collation.
Solution: You have to use a `CS` collation: `SELECT * FROM fn_helpcollations() WHERE description LIKE N'%case-sensitive%'`.
Note: There is a database collation and column level collation. And, there is, also, a server ... | If you want your query to be case sensitive on few occasions only, then you can try below query:
```
SELECT *
FROM TableName
where Col1 = 'abcdEfhG' COLLATE SQL_Latin1_General_CP1_CS_AS
```
Just add **"COLLATE SQL\_Latin1\_General\_CP1\_CS\_AS"** in front of the query. | SQL Server Like Query not case sensitive | [
"",
"sql",
"sql-server",
"sql-server-2008",
"sql-server-2008-r2",
"sql-server-2012",
""
] |
I have the following database schema:
```
CREATE TABLE public.sgclasstab_id67
(
oid bigint NOT NULL,
att_1113 bigint,
att_1114 bigint,
att_1115 character varying(500),
att_1116 character varying(2000),
att_1578 double precision,
CONSTRAINT sgclasstab_id67_pkey PRIMARY KEY (oid)
)
CREATE T... | Taking joop's answers into account, i came up with the following cleaned up and modified version of my first statement
```
UPDATE sgclasstab_id68 SET att_1496 = (
SELECT sgclasstab_id67.att_1115
FROM sgclasstab_id67, sggeofacelist, sggeopointlist
WHERE ((sgclasstab_id67.att_1114=sggeofacelist.oid ))
... | [not an answer]
FYI: the cleaned-up query(hope I didn't make any misstakes):
```
UPDATE sgclasstab_id68 dst
SET att_1496 = (
SELECT cla.att_1115
FROM sgclasstab_id67 cla
JOIN sggeofacelist fac ON cla.att_1114 = fac.oid AND fac.oid = cla.att_1114
JOIN sggeopointlist pnt ON fac.feature && (pnt.feature) ... | "Unfavourable" execution plan with Postgres and PostGIS | [
"",
"sql",
"postgresql",
"postgis",
""
] |
Let's say I have some timestamp fields in a column that look like this "02-JUL-14 10.36.07.713000000 PM".
Is there a way for me to left-click the column in that table and do a search that contains "JUL" so that I only have rows show up that contain "JUL"?
I have read articles of people saying to include % and ' chara... | Paste
```
like '%JUL%'
```
in the filter field, and whatever values in that column which contain "JUL" will show up.
The
<http://www.thatjeffsmith.com/archive/2011/11/sql-developer-quick-tip-filtering-your-data-grids/>
link from @OldProgrammer contained the solution that I found. There may be more helpful things in ... | Type
```
to_char(TIME_OF_ENTRY) like '%JUL%'
```
in the filter field above. | How to filter a column in Oracle Sql Developer | [
"",
"sql",
"oracle-sqldeveloper",
""
] |
I have the following table:
```
Object Field Values
------------------------------------
1 1 A;A;A;B;A;A
2 1 A;B;C;C
2 2 X
3 1 X;Y;Z
3 2 V;V;V;V;V;V;V;V;V;V;V
```
How can I select from this table only the unique values from the concatenated `values`? So:
```
O... | To do this first create a split function. This is the one I use but if you search the internet (or even SO) for "SQL Server Split Function" you will find a number of alternatives if you don't like this:
```
ALTER FUNCTION [dbo].[Split](@StringToSplit NVARCHAR(MAX), @Delimiter NCHAR(1))
RETURNS TABLE
AS
RETURN
(
... | Here is a standalone solution:
```
DECLARE @t table(Object int, Field int, [Values] varchar(max))
INSERT @t values
(1, 1, 'A;A;A;B;A;A'),
(2, 1, 'A;B;C;C'),
(3, 1, 'X'),
(4, 1, 'X;Y;Z'),
(5, 1, 'V;V;V;V;V;V;V;V;V;V;V')
SELECT t.Object, t.Field, x.[NewValues]
FROM @t t
CROSS APPLY
(
SELECT STUFF((
SELECT distin... | Delete duplicate values from concatenated string | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
If I have a table with columns: a, b, c and later I do a ALTER TABLE command to add a new column "d", is it possible to add it between a and b for example, and not at the end?
I heard that the position of the columns affects performance. | It's not possible to add a column between two existing columns with an ALTER TABLE statement in SQLite. This [works as designed](http://www.sqlite.org/lang_altertable.html).
> The new column is always appended to the end of the list of existing
> columns.
As far as I know, MySQL is the only SQL (ish) dbms that lets y... | With every sql platform I've seen the only way to do this is to drop the table and re-create it.
However, I question if the position of the column affects performance... In what way would it, what operations are you doing that you think it will make a difference?
---
I will also note that dropping the table and recr... | Sqlite ALTER TABLE - add column between existing columns? | [
"",
"sql",
"performance",
"sqlite",
"alter-table",
""
] |
My current query pulls something like this:
```
╔════════════════════════════════════════╗
║ A Monthly 123 123 123 123 123 123 ║
║ B Quarterly 123 123 123 123 123 123 ║
║ C SemiAnnual 123 123 123 123 123 123 ║
║ D Annual 123 123 123 123 123 123 ║
╚════════════════════════════════════════╝
```
The prob... | This ended up solving the issue:
```
Select
MODE,
SUM(POLCT) AS POLCT,
SUM(RDRCNT ) AS RDRCNT,
SUM(INCCNT) AS INCCNT,
SUM(INCINS ) AS INCINS,
SUM(INS_AMOUNT) AS INS_AMOUNT,
SUM (PREM) AS PREM FROM
(SELECT CASE
when mode = '12' then 'D Annual'
when mode = '03' then 'B Quarterly'
when mode = '0... | You need to create a pseudo table with all the values you want in:
```
SELECT *
FROM ( SELECT 'D Annual' AS Mode UNION ALL
SELECT 'B Quarterly' AS Mode UNION ALL
SELECT 'C SemiAnnual' AS Mode UNION ALL
SELECT 'A Monthly' AS Mode UNION ALL
SELECT ' ' AS Mode
... | How to pull summary data even when there is no rows returned? | [
"",
"sql",
"sum",
""
] |
I have two table.
1st table => member {member\_id, name, active}
2nd table => savings {savings\_id, member\_id, month, year, amount, type, paid}
Member Table
```
+-----------+--------+--------+
| member_id | name | active |
+-----------+--------+--------+
| 105 | Andri | 1 |
| 106 | Steve | 1 ... | The problem is you're forming the full join product before summation. So if there is more than one row in more than one of your `savings` tables you will end up with duplication. If you [perform the join without summation](http://sqlfiddle.com/#!2/9eca9/72), you can clearly see what is going on. There are two ways arou... | You probably do not need multiple left joins and could be done as
```
SELECT
m.member_id,
m.name,
SUM(case when s.type= 1 then s.amount end) as savings1,
SUM(case when s.type= 2 then s.amount end) as savings2,
SUM(case when s.type= 3 then s.amount end) as savings3,
SUM(case when s.type= 4 then s.amount end) as saving... | Multiple Left Join on same table | [
"",
"mysql",
"sql",
"left-join",
""
] |
SQL Query:
**Aim:**
> Write a SQL query to retrieve the address of highest rated Phills
> Coffee in United States addressing format.
```
id name house street city state zip country rating
1 Best Buy 34 Main St Carson CA 98064 USA 9
2 Phills Coffee ... | US address format would be like:
4568 Sepulveda Blvd, Torrance, CA 50833 USA.
So your select would look like:
SELECT CONCAT(house, ' ', street, ', ', city, ', ', state, ' ', zip, ' ', country)
FROM table
WHERE name="Phills Coffee"
ORDER BY rating DESC LIMIT 1 | You've been asked to retrieve the address, and in United States addressing format. So use that :
> SELECT CONCAT(street,' ','country', ',') ...
Dont know what is the US addressing format, but use concat to get it done. Your WHERE condition and ORDER BY are OK | SQL Query to find highest rated | [
"",
"mysql",
"sql",
""
] |
Here is a sample Database
```
First_name country
Andy US
Manu India
Paul Pakistan
Ramesh Pakistan
Rich India
```
So, what i want is to select all records from the above table and display according to name.
Like :-
I want to select person name to be display fi... | Use a CASE statement to give each record a sortkey. 0 for a country match, 1 for a mismatch, so the desired country comes first.
```
select *
from mytable
order by case when country = @country then 0 else 1 end, first_name
``` | May be something like this
```
Select * From Table1
Order By CASE WHEN country = 'INDIA' THEN 0
WHEN country = 'US' THEN 1
Esle 2
END;
```
Or You can use **[FIELD](http://www.w3resource.com/mysql/string-functions/mysql-field-function.php)**
```
Select * From Table1 Order By FIELD... | How to sort based on keyword first? | [
"",
"mysql",
"sql",
"sorting",
"select",
"sql-order-by",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.