Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Having the following two tables in a MySQL Database: ``` USER - ID - Name GAME1 - ID - UserID - Score - Rank ``` This is what I need in a view: ``` - User.ID - User.Name - Game1.ID as MaxScoreGameID - Max(Game1.Score) as MaxScore - Game1.ID as BestRankGameID - Min(Game1.Rank) as BestRank ``` I got it w...
``` SELECT u.ID , u.Name , (SELECT sub.ID from Game1 as sub where sub.UserID = u.ID ORDER BY sub.Score desc LIMIT 1) as MaxScoreGameID , Max(Game1.Score) as MaxScore , (SELECT sub2.ID from Game1 as sub2 where sub2.UserID = u.ID ORDER BY Rank asc LIMIT 1) as BestRankGameID , Min(Game1.Rank) as B...
You could use a filtering join. The example is just for score, but you can add a second filtering join for rank. ``` select u.name , g1.ID as MaxScoreGameID , g1.Score as MaxScore from User u join ( select UserID , max(Score) as maxScore from Game1 group by ...
Query to get identifier and aggregate function value of a row
[ "", "mysql", "sql", "group-by", "aggregate", "greatest-n-per-group", "" ]
I've got a single table DB with 100K rows. There are about 30 columns and 28 of them are varchars / tiny text and one of them is an int primary key and one of them is a blob. My question, is in terms of performance, would it be better to separate the blob from the rest of the table and store them in their own table wi...
This totally depends on data usage. If you need the data everytime you query the table, there is no difference in haviong a separate table for it (as long as blob data is unique in each row - that is, "as long as the database is normalized"). If you don'T need the blob data but only metadata from other columns, there...
If you do `SELECT * FROM table` (which you shouldn't if you don't need the BLOB field actually) then yes, the query will be faster because in that case pages with BLOB won't be touched. If you do frequent `SELECT f1, f2, f3 FROM table` (all fields are non-BLOBs) then yes, storing BLOBS in a separate table will make th...
MySQL DB normalization
[ "", "mysql", "ios", "sql", "sqlite", "core-data", "" ]
``` ID ID_A Status 175 473 2 174 473 1 173 455 2 170 412 2 169 397 1 168 393 2 173 391 2 ``` Thats my example table. As result I want it to display only entries with Status=1, Grouped by ID\_A. It must not contain the results with Status=2! Result should look like this...
This is sometimes called an *exclusion join*. You do an outer join to try to find the row that would invalidate your condition. Where there is no such row, the outer join will put NULL into all the columns of the joined table, and then you have a match. ``` SELECT t1.ID_A, t1.Status FROM exampletable AS t1 LEFT OUTER...
You can do this with an aggregation and a `having` clause: ``` select id_a, group_concat(status) as statuses from table t group by id_a having sum(status = 2) = 0; ```
SQL: only show entry if there is no other entry with special different value in same table
[ "", "mysql", "sql", "select", "count", "distinct", "" ]
I currently have two tables in my database, one for the values (using Foreign Keys) and one for their translations (same table has translation for more than one attribute type). I am trying to perform a single inner join from the Values table to the Translations table and translate two or more fields. I know this is ...
You can do this by joining twice to the `translation` table: ``` SELECT toff.name as office, tseg.name as segment, v.`sum` from values v join translation toff on v.office = toff.value and toff.attribute = 'office' join translation tseg on v.segment = tseg.value and tseg.attribute = 'segment'; ``` ...
Looks like you want to join the `Translation` table back to itself through the `Values` table: ``` SELECT o.name office, s.name segment, v.sum FROM Translation o INNER JOIN Values v ON o.value = v.office INNER JOIN Translation s on v.segment = s.value ```
Select inner join with multiple fields from same table
[ "", "sql", "" ]
We're trying to find data errors in a MySQL database and I can't figure out a way to handle this without thrashing the database. Here's a mockup of the data: ``` Table: EXAMPLE +-----+------+-------+ | ID | PID | YEAR | +-----+------+-------+ | | | | | 001 | A | 2014 | | | | | | 0...
You can do this with an `exists` subquery instead: ``` select e.* from example e where exists (select 1 from example e2 where e2.pid = e.pid and e2.year <> e.year ); ``` To have this run faster, create an index on `example(pid, year)`. If you just want all...
``` SELECT EXAMPLE.* FROM EXAMPLE INNER JOIN (SELECT PID FROM EXAMPLE GROUP BY PID HAVING COUNT(DISTINCT Year)>1) Dup ON Example.PID = Dup.PID ``` Please see fiddle [here](http://sqlfiddle.com/#!2/68e24/1).
Return All MySQL Rows Where colA is Duplicated by colB Isn't
[ "", "mysql", "sql", "" ]
I have a table with the columns FacilityID, servername with the facilityID being the primary key and the servername being the server that the data for that facility is located on. When we add a new facility, I want to be able to select the servername used the least number of times, but I am not sure how to do that. ...
depends on database, in mssql i would do: ``` select top 1 FacilityID,count(servername) over (partition by FacilityID) as Cardinality from tablename order by Cardinality asc ```
You could use the COUNT and then outside the MIN. ``` Select MIN (x.myCount ) FROM ( select COUNT (servername) as myCount from ... GROUP BY servername) as x ```
How to Select the value duplicated the least number of times in SQL
[ "", "sql", "" ]
Ok. This is a homework exercise . I've tried looking up everything and can't figure out the error. The schema is as follows: ``` course{ course_id title dept } section{ course_id semester year } ``` The course table has all the offered courses. The section table has what courses are offered, past and future. ...
You can do *(from most to less preferable)* ``` SELECT c.course_id, COUNT(s.course_id) total FROM course c LEFT JOIN section s ON c.course_id = s.course_id GROUP BY c.course_id; ``` or ``` SELECT c.course_id, COALESCE(total, 0) total FROM course c LEFT JOIN ( SELECT course_id, COUNT(*) total FROM se...
You just want to base your query off of the sections, and LEFT JOIN which tallies up even sections that have not yet had courses on the right side of the join ``` SELECT section.course_id, COUNT(course.id) FROM section LEFT JOIN course ON course.course_id = section.course_id GROUP BY section.course_id ```
Basic mySQL - Don't know how to show all results including 0
[ "", "mysql", "sql", "database", "" ]
I have a table that has labels and some codes next to them: ``` id | label | code 1 | foo | 21 2 | foo | 33 3 | foo | 33 4 | foo | 13 5 | foo | 13 6 | foo | 33 7 | bar | 13 8 | bar | 13 9 | bar | 33 10 | smt | 33 11 | smt | 13 ``` I would ...
My similar solution as @TechDo, but with 1 subquery ``` SELECT frequency,label,code FROM ( SELECT count(*) AS frequency ,MAX(COUNT(*)) OVER (PARTITION BY label) AS Rnk ,label ,code FROM myTable GROUP BY label, code ) x WHERE frequency=Rnk ORDER BY frequency DESC ``` SQLFiddle [here](http://sqlfi...
Please try: ``` SELECT * FROM( SELECT *, MAX(frequency) OVER(PARTITION BY label) Col1 FROM( SELECT count(*) frequency, label, code FROM myTable GROUP BY label, code )x )xx WHERE frequency=Col1 ```
SQL select top counts for grouped rows
[ "", "sql", "sql-server", "group-by", "" ]
When i run *sql query* such as; ``` Select F1 as name, F2 as phone from Table where condition = true ``` If `F2 = 0` i need to that field to be `No Phone Number` instead of `null` or `0`
You can do that with a CASE statement: ``` SELECT CASE WHEN F2 = '0' THEN '(No Phone Number)' ELSE F2 END AS Phone ... ```
``` SELECT CASE WHEN F2 = '0' OR F2 IS NULL THEN '(No Phone Number)' ELSE F2 END AS Phone ```
SQL Query put a word in a field instead of 0?
[ "", "sql", "database", "" ]
There are countries in MySQL table: ``` id | title 1 | USA 2 | Spain 3 | Italy 4 | Canada ``` I need to select Italy on the top of list and other countries sorted by title below. But 'order by' doesn't work. ``` (SELECT * FROM countries WHERE id = 3) UNION (SELECT * FROM countries WHERE id != 3 ORDER BY title)...
First sort your data based on whether it is Italy or not, getting Italy first. Then sort based on the title. ``` SELECT * FROM countries ORDER BY title='Italy' DESC, title ``` (The only trick you have to know -- or experiment with -- is that `FALSE` comes before `TRUE`, and hence the `DESC` in the code. I guess that ...
you can try this ``` SELECT * FROM countries ORDER BY case when id !=3 then `title` end asc , case when id =3 then `title` end asc ; ```
How to sort in a different way
[ "", "mysql", "sql", "" ]
Am searching for a way to emulate the "rollup" available in other sql based dbms. To be clear, I know how to get running subtotals and this is **not** what I am after. I also know that I can probably do this programmatically. However, if it is possible to do with one (or a couple) of sql statements I would rather do th...
Here is a way that works to emulate rollup under sqlite. I stumbled upon an answer from 2007 on a database [forum](http://www.daniweb.com/web-development/databases/ms-sql/threads/255430/results-with-subtotals-and-grandtotal) asking about subtotals and grand totals. I'll summarize here with my simplified case. I have a...
Had a same problem myself - emulating `subtotals` in `SQLite3`, and here`s, what I came to: ``` with counter(numm)as(select 1 union all select numm+1 from counter where numm<34), str(par,node)as(select 1, numm from counter where numm in(2,5,8,11)union select 11, numm from counter where numm in(12)union select 12, nu...
Sqlite: subtotals in own row aka "rollup"
[ "", "android", "sql", "sqlite", "rollup", "" ]
80-90% of the time I spend in SQL Server Management Studio is spent dealing with the same 5 or 6 tables/views/stored procedures, out of the 100+ in some databases. It would be wonderfully helpful if there were a quick way to access those few through the GUI, instead of having to scroll all around and toggle the Tables...
I can think of two ways that may help get you to the right objects in the SSMS Object Explorer. Both are SSMS addins. 1) Use the free [SQL Search](http://www.red-gate.com/products/sql-development/sql-search/) - when you need to locate an object, press Ctrl-Alt-D, type the name of the object, arrow down until you highl...
One way to do this - and I use it all the time for the same reasons you cited - is to set up **Filters** (one time activity per object type) in SSMS. For tables, right click the **Tables** node under your database, and select **Filter** -> **Filter Settings**. Then enter your filter criteria and save that filter. Now ...
Is there a way to favorite or star frequently-used tables in SSMS 2012?
[ "", "sql", "sql-server", "ssms", "ssms-2012", "" ]
I have a table which has two columns. ``` create table txns( person varchar(255), fruit varchar(255) ); ``` This is a log table. I have sqlfiddle [here](http://sqlfiddle.com/#!4/e4bbd/6). This is as far as I am able to get with the sql query. In essence, For every person, which is the most frequent fruit he ...
Following query would run both in Oracle and MySQL. ``` select k.person, k.fruit from ( select person,fruit,count(fruit) as cnt from txns group by person,fruit ) k join ( select t.person,max(t.cnt) mxCnt from ( select person,fruit,count(fruit) as cnt from txns group by person,fruit )t group b...
[SQL Fiddle](http://sqlfiddle.com/#!4/e4bbd/118) **Oracle 11g R2 Schema Setup**: ``` create table txns( person varchar(255), fruit varchar(255) ); insert into txns values ('alpha','apple'); insert into txns values ('charlie','cherry'); insert into txns values ('bravo','banana'); insert into txns values ('a...
Group and choose max pair SQL
[ "", "mysql", "sql", "oracle", "hadoop", "" ]
I have need to automate the process of database upgrade process. So by getting the column structure of a table i need to create update/insert/create sql statement's . BY problem was i am getting duplicate column name as constrains are also coming in the list which i don't need. So is there a way to restrict constraint...
The problem is that you are including all indexes on the column. Consider this simple table: ``` CREATE TABLE #T (ID INT NOT NULL CONSTRAINT PK_T_ID PRIMARY KEY); CREATE INDEX IX_T_ID ON #T (ID); ``` When you run an adaption of you query: ``` SELECT c.name, i.name, i.is_primary_key FROM tempdb.sys.columns c LEFT...
What happens if you use the "DISTINCT"? so ``` SELECT distinct c.NAME... ```
Get list of all columns with complete details (Identity, nullabel,primary key) in sql server without duplicate column
[ "", "sql", "sql-server", "sql-server-2008", "" ]
``` create table tbl ( id int, comment varchar(255), primary key (id) ); insert into tbl (id, comment) values ('1', 'dumb,'); insert into tbl (id, comment) values ('2', 'duuumb,'); insert into tbl (id, comment) values ('3', 'dummb'); insert into tbl (id, comment) values ('4', 'duummb'); insert into tbl (id, comm...
This will work for your particular example: ``` select comment from tbl where soundex(comment) like '%D510%' or comment like '%dumb%'; ``` It won't find misspellings in the comment. EDIT: You could do something like this: ``` select comment from tbl where soundex(comment) = soundex('dumb') or soundex(substr...
Can you try with MySQL [REGEXP](http://dev.mysql.com/doc/refman/5.1/en/regexp.html)? Is a good solution to find a specific word into text. You can use **[[:<:]]** and **[[:>:]]** as word boundaries: ``` SELECT comment FROM tbl WHERE comment REGEXP '[[:<:]]dumb[[:>:]]' ```
In MySQL how to write SQL to search for words in a field?
[ "", "mysql", "sql", "soundex", "" ]
Table `A` - column `B [DateTime]` Need list users in that table, ordering at nearest birthday. Users who have already made birthday should be at the end of the list considering them for the following year. ``` select B from A (order by/where)? ``` Table Example ``` USER DATE MARCELO 1988-04-11 RICARDO 1965-12...
**Test Data** ``` DECLARE @TABLE TABLE(Name VARCHAR(100),Dob DATETIME) INSERT INTO @TABLE VALUES ('Mark', '19961017'),('Josh', '19801119'),('Sam', '19700709'), ('Vicky', '19500210'),('Dom', '19890308'),('Paul', '19840401') ,('Nick', NULL) ``` **Query** ``` SELECT Name, CAST(MONTH(Dob) AS NVARCHAR(2)) ...
``` select name, birthdate from yourtable where birthdate is not null order by datepart(dy,dateadd(d,- DATEPART(dy, getdate()),birthdate )) ```
SQL Server : list by Nearest Birthday
[ "", "sql", "sql-server", "t-sql", "" ]
``` SELECT * FROM `articles` `t` LEFT OUTER JOIN `category_type` `category` ON (`t`.`category_id`=`category`.`id`) WHERE ( t.status = 6 AND t.publish_on <= '2014-02-14' AND t.id NOT IN (13112,9490,9386,6045,1581,1034,991,933,879,758) AND t.category_id IN (14) ) ORDER BY t.id DESC LIMIT 7; ``` ...
First thing => use `where` instead of `inner join`. Because `where` is faster than `inner join` query. Second thing => use `indexes` for the `frequently searched columns`. As in your example you search on the basis of status, publish\_on besides id as `primary index`.
If you are using mysql then you can try propose table structure option in the phpmyadmin which can help you to decide valid data types for your column names. This could help you to optimize your query processing. query processing time depends on many things like: database server load, amount of data in the table and t...
Mysql query exicution time is too slow
[ "", "mysql", "sql", "" ]
I have a following table ``` Name Amount Paid ----------------------- Ali 500 500 Baba 700 100 Cam 300 Null Dave Null Null ``` I want the following desired result: ``` Name Amount Paid -------------------- Baba 700 100 Cam 300 Null ``` I wrote the followin...
Will it work if you treat `NULL` as Zero *(assuming that is valid business logic)*: ``` SELECT Name, ISNULL(Amount,0), ISNULL(Paid,0) as Paid FROM Table_1 WHERE ISNULL(Paid,0) <> ISNULL(Amount,0) ```
Well, `null <> null` is `null`, and `null = null` is also `null`, resulting in a false condition. Confusing? You have to check for null separately, using the `is null` operator: ``` select Name, Amount, Paid from Table_1 where (Paid is not null and Amount is not null and Paid <> Amount) or not (Paid is null an...
SQL query - dealing with Null Value
[ "", "sql", "sql-server", "" ]
Everything about my VS 2013 install appears to be working correctly except when I right click on a table in Server Explorer. I am trying to use the data tools to view the table, which is in a MS SQL database. Here is the message VS 2013 pops when I right click: ``` The 'Microsoft SQL Server Data Tools' package did not...
Go to 'Add/Remove Programs' in Control Panel, search for "*Microsoft SQL Server Data Tools*" and repair. Worked for me.
And just in case none of those work, you can go to the **[Download Latest SQL Server Data Tools](https://msdn.microsoft.com/en-us/library/mt204009.aspx)** Microsoft page itself. It lists out the versions of the tool set for each version of Visual Studio
Microsoft SQL Server Data Tools package did not load correctly
[ "", "sql", "sql-server", "visual-studio-2013", "sql-server-data-tools", "" ]
Is it possible to use between operator within a CASE statement within a WHERE Clause ? For example in the code below, the condition should be pydate between (sysdate-12) and (sysdate-2) if its a monday and pydate between (sysdate-11) and (sysdate-1) if its a tuesday and so on. But the following doesn't work. May be the...
You can apply the logic you are attempting, but it is done without the `CASE`. Instead, you need to create logical groupings of `OR/AND` to combine the `BETWEEN` with the other matching condition from your case. This is because `CASE` is designed to return a value, rather than to dynamically construct the SQL inside i...
This is hard to write using a `case`. Just do: ``` where pricekey = 'JUF' and ((to_char(to_date(sysdate,'DD-MON-YY'), 'DY') = 'MON' and pydate between to_date(sysdate-12,'DD-MON-YY') and to_date(sysdate-2,'DD-MON-YY') ) or (to_char(to_date(sysdate,'DD-MON-YY'), 'DY') = 'TUE' and p...
Using 'Between' operator after 'THEN' within 'CASE' statement within 'WHERE' Clause
[ "", "sql", "oracle", "" ]
I need some help with SQL query creation. I have data like ``` EN 771-2:2011 EN 197-1:2011 EN 295-1:2013 771-1:2011 EN 54-24:2008 EN 492:2012 EN 54-25: 2008 EN 331:1998 EN 534:2006+A1:2010 EN 588-2:2001 EN 179:2008 EN 598:2007+A1:2009 EN 621:2009 EN 682: 2002 ``` Is possible create ORDER BY causule, when result of o...
You'd have to formally define via regexp what *exactly* is "bold" or "italic". If you assume that the first group of digits is the first variable to order on and the second is the second: ``` ORDER BY substring(col,'\d+')::int, substring(col,'\d+[^\d]+(\d+)')::int; ``` Or alternatively, if your definition is that th...
Yes, substring as you say, but then you have to cast it to integer so that a numeric order is being used (which seems to be what you want). Untested, try this in the order by: cast(substring(YOURFIELDNAME from '\s\*\d+-') as integer) It uses a regular expression: \s for a space \* to make it optional \d for digits ...
SQL order by part of substring
[ "", "sql", "postgresql", "sql-order-by", "hql", "" ]
I have the following mySQL Query which returns a list of ID's. I want to delete the rows with each ID of the list from the table "serverking\_user" ``` SELECT serverking_user.id FROM (serverking_user INNER JOIN serverking_logins ON serverking_user.id=serverking_logins.uid) WHERE serverking_logins.time < 3600 GROUP BY ...
It has been a while since I have done MySQL development, but if I remember correctly this should work for you: ``` DELETE su FROM serverking_user su INNER JOIN serverking_logins sl ON su.id=sl.uid WHERE sl.time < 3600 GROUP BY su.id HAVING COUNT(sl.login) = 1 ``` In general, if you want to delete records from a singl...
``` DELETE FROM serverking_user WHERE EXISTS (SELECT * FROM (serverking_user INNER JOIN serverking_logins ON serverking_user.id=serverking_logins.uid) WHERE serverking_logins.time < 3600 GROUP BY serverking_user.id HAVING COUNT(serverking_logins.login) = 1) a ```
SQL: Delete by result of Select with Join
[ "", "mysql", "sql", "sql-delete", "" ]
I tried various alterations to get the right query date format. Below is one of them. The below date is actually filled in by string substitution from a java program. I need to be able to interpret it and run the query. Currently the query fails with the below error: ``` [Error] Execution (48: 18): ORA-01841: (full) y...
You cant use to\_date for timezone. try this. ``` SELECT TO_TIMESTAMP_TZ('MON JAN 01 12:00:00 EST 1990', 'DY MON DD HH24:MI:SS TZR YYYY') FROM duAL; ```
I try, removed the **Mon** and **EST** ``` SELECT to_date('Jan 01 12:00:00 1990', 'MON DD HH:MI:SS RRRR') FROM dual ```
How can I format an oracle query with this date?
[ "", "sql", "oracle", "" ]
How can I **list all the tables** of a PostgreSQL database and **order them by size**?
``` select table_name, pg_size_pretty(pg_total_relation_size(quote_ident(table_name))), pg_total_relation_size(quote_ident(table_name)) from information_schema.tables where table_schema = 'public' order by 3 desc; ``` This shows you the size of all tables in the schema `public` if you have multiple schemas, you ...
This will show you the schema name, table name, size pretty and size (needed for sort). ``` SELECT schema_name, relname, pg_size_pretty(table_size) AS size, table_size FROM ( SELECT pg_catalog.pg_namespace.nspname AS schema_name, relname, pg_relation_size(pg_catalog...
postgresql list and order tables by size
[ "", "sql", "postgresql", "postgresql-9.3", "" ]
How can I enumerate multiple date ranges in SQL Server 2008? I know how to do this if my table contains a single record ``` StartDate EndDate 2014-01-01 2014-01-03 ;WITH DateRange AS ( SELECT @StartDate AS [Date] UNION ALL SELECT DATEADD(d, 1, [Date]) FROM DateRange WHERE [Date] < @EndDate ...
Well, let's see. Define the ranges as a table. Then generate the full range of dates from the first to the last date. Finally, select the dates that are in the range: ``` with dateranges as ( select cast('2014-01-01' as date) as StartDate, cast('2014-01-03' as date) as EndDate union all select '2014-01-05'...
You could grab the min and max dates first, like so: ``` SELECT @startDate = MIN(StartDate), @endDate = MAX(EndDate) FROM YourTable WHERE ... ``` And then pass those variables into your date range enumerator. *Edit...* Whoops, I missed an important requirement. See the accepted answer.
SQL Server 2008 - Enumerate multiple date ranges
[ "", "sql", "sql-server-2008", "" ]
## here is my sql ``` SELECT * FROM ( SELECT Row_number() OVER (ORDER BY [bbajobs].JID) AS RowNumber ,[BBAJobs].[JID] ,[AccountReference] as [Acc Ref] ,[BBAJobs].[OEReference] as [OERef] ,[JobType],[JobState] ,[JobShippedDate] ,[UPSShippingNumber] ,[CustomerNam...
If you want to select 20 rows from the subquery, then you need to make sure that any conditions that filter the rows are applied before/at the same time as you number the rows. Move the condition inside the subquery: ``` SELECT * FROM (SELECT Row_number() OVER ( ORDER BY [bbajobs].jid ) AS RowNumb...
The way this is written, the subquery 'x' is returning an ordered dataset. Once that dataset is returned, the following line is filtering it to rows that match it: ``` AND x.jid IN (SELECT CONVERT(VARCHAR, data) AS [JID] FROM dbo.Split1('33180,33265,33047', ',')) ``` Moving this condition within the 'x' subquery shou...
SQL server wrong Row Number is showing
[ "", "sql", "sql-server", "" ]
say i have this result to this query.. ``` customername p8 p12 p750 p1 m8 customer1 5 48 4 4 4 customer2 4 2 5 43 customer3 4 -3 ``` now i want to ask if is there a way that i could add all the rows to form something like this: ``` customerna...
``` create table tbl1 (m1 int, m2 int); insert into tbl1 (m1,m2) values (25,50),(30,43); ``` **Query:** ``` select m1,m2, (m1+m2) as total from tbl1; ``` # [Demo](http://sqlfiddle.com/#!2/348b2/1)
Sum up the fields and use an alias to name the dynamic column in your select ``` select coalesce(p8,0)+ coalesce(p12,0)+ coalesce(p750,0)+ coalesce(p1,0)+ coalesce(m8,0) as total from your_table ``` If some of your column allow `null` then you have to use a function like `coalesce` to repl...
sum sql rows and add to a new column
[ "", "sql", "" ]
I have 2 mysql databases 1. DB1 2. DB2 I want to select all contact values from **contact\_mst** table under **DB1**, and then insert all those values inside **contact\_mst** table under **DB2**. I do not want to copy the **contact\_id** field for some reason and want to keep them incremental, but also do not want th...
Below is the sample code for inserting records to table tab2 where value of column `a` is a sequence of integer and value of column b is same as value of column b of tab1 ``` create table tab1 ( a int, b int ); create table tab2 ( a int, b int ); insert into tab1 values (10,20),(30,40); ``` tab1 contents...
try this ``` INSERT INTO DB2.contactsmaster (Company_id, Contact_id, Contact_person) VALUES( 1, (SELECT COALESCE(MAX(Contact_id),0)+1 FROM DB2.contactsmaster), (SELECT Contact_person FROM DB1.contact_mst LIMIT 1) ) ```
How to do Insert-Select with manual incremental value?
[ "", "mysql", "sql", "" ]
I'm quite new to SQL Server, but I still manage to do most of the things I need. However, there is one thing I just can't understand and that it working with dates. I have a database like this used for recording sales: ``` **Sales** [index] int timestamp datetime username varchar(10) type int amo...
``` SELECT DATENAME(MONTH,[timestamp]) [Month] ,COUNT(DISTINCT CASE WHEN YEAR([timestamp]) = YEAR(GETDATE()) THEN username ELSE NULL END) CurrentYear ,COUNT(DISTINCT CASE WHEN YEAR([timestamp]) = YEAR(GETDATE())-1 THEN username ELSE NULL END) Las...
For your first question : ``` SELECT CONVERT(varchar, DATEADD(dd, 0, DATEDIFF(dd, 0, [timestamp])), 104) as [timestamp], COUNT([username]) as a FROM [sales] WHERE [timestamp] >= DATEADD(day,-7, GETDATE()) GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, [timestamp])) ORDER BY DATEADD(dd, 0, DATEDIFF(dd, 0, [timest...
SQL Server and working with dates, year and previous year
[ "", "sql", "sql-server", "datetime", "" ]
Running the following query: ``` SELECT exists ( SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'public' ) AS schema_exists; ``` I am getting always `FALSE`, even if the public schema exists. How should i check if this schema exists? **EDIT** I am usin...
The information from `information_schema.schemata` depends on the role you're connected with, so it's not really the right view to query to discover schemas in general. The [doc on `information_schema.schemata` in 9.3](http://www.postgresql.org/docs/9.3/static/infoschema-schemata.html) says: > The view schemata conta...
I guess you can't see public schema because of the database role you are using to test schema existence. `information_schema.schemata` is actually a view with the following definition: ``` SELECT current_database()::information_schema.sql_identifier AS catalog_name, n.nspname::information_schema.sql_identifi...
How to check if PostgreSQL public schema exists?
[ "", "sql", "postgresql", "schema", "" ]
Want to have a counter field that starts with a character followed by a number as a regular counter, but the counter should start with x number of zeros. Example: ``` L00001 L00002 L00003 ``` Is it possible to construct such counters in sql server? **Update:** It should be auto generated counter values that is inc...
One possible trick, use a computed column: ``` --DROP TABLE MyTable CREATE TABLE MyTable ( MyTableId int not null identity(1,1) ,MyTableKey as 'L' + right('00000' + cast(MyTableId as varchar(5)), 5) persisted constraint PK_MyTable primary key clustered ,SomeData varchar(50) ) ``` Column M...
hi david use this query for create your table ``` CREATE TABLE [dbo].[Emp]( [ID] [int] IDENTITY(1,1) NOT NULL, [Name] [varchar](50) , [AutoGeneratedColumn] AS ('L'+right(replicate('0',(5))+CONVERT([varchar](5),[ID],0),(5))) ) ON [PRIMARY] ```
Specialized counter field in Sql Server
[ "", "sql", "sql-server", "" ]
I'm not sure how to accurately summarize the problem I'm having in one sentence, but it is fairly simple to describe (below). Here are three tables associated with foreign keys on the last table: tbl\_village: ``` villageID | village_name 1 | Happy Village 2 | Sad Village ``` tbl\_setting: ``` s...
You want to move the conditions to the `having` clause: ``` SELECT s.settingID, s.setting_name FROM tbl_neighbourhood n JOIN tbl_setting s ON s.settingID = n.settingID_fk GROUP BY s.settingID, s.setting_name HAVING sum(n.villageID_fk = 1) > 0 and sum(n.villageID_fk = 2) > 0; ``` Each conditions...
You want to `JOIN` neighbourhood against itself: ``` SELECT s.settingID, s.setting_name FROM tbl_neighbourhood n1 JOIN tbl_neighbourhood n2 ON (n1.settingID_fk = n2.settingID_fk AND n1.villageID_fk < n2.villageID_fk) JOIN tbl_settings s ON s.settingID = n1.settingID_fk WHERE n1.villageID_fk IN (1, 2) GROUP BY...
MySQL SELECT where common foreign key among many
[ "", "mysql", "sql", "" ]
The following procedure takes forever. Its purpose is to concatenate a list of IDs into one string. ``` declare @validatedIDList nvarchar(max) SELECT @validatedIDList = COALESCE(@validatedIDList + ', ', '') + CAST(si.SelectedID AS nvarchar(50)) FROM dbo.SelectedID si ``` dbo.SelectedID is a table with only ...
Running this on a table containing consecutive integers from `1 - 60,000` takes just over 5 minutes on my machine. ``` DECLARE @validatedIDList NVARCHAR(max) SELECT @validatedIDList = COALESCE(@validatedIDList + ', ', '') + CAST(si.SelectedID AS NVARCHAR(50)) FROM dbo.SelectedID si SELEC...
``` DECLARE @SelectedID TABLE (IDs INT) INSERT INTO @SelectedID VALUES (1),(2),(null),(4),(5),(null),(7) declare @validatedIDList nvarchar(max) SET @validatedIDList = STUFF((SELECT ', ' + CAST(si.IDs AS nvarchar(50)) FROM @SelectedID si FOR XML PATH('')),...
Why is the combination of coalesce and cast so slow in concatenation?
[ "", "sql", "sql-server", "" ]
I'm trying to retrieve data from from a table such as: ``` col1 col2 col3 col4 col5 col6 aaaa bbbb cccc oooo eric date1 aasa bcbb ccfc ooho Samm date2 aaaa bbbb cccc oooo eric date3 aaaa bbbb cccc oooo Samm date4 aaaa bbbb cccc oooo eric date5 ``` I would li...
``` select * from tbl where col5 in (select col5 from tbl where col6 = (select max(col6) from tbl)) ```
I'm not sure if I fully understand the question here... You want to first filter the query by "col5" and then sort it descending by the dates in "col6"? In that case, the query would be ``` SELECT * FROM tbl WHERE col5 = 'eric' ORDER BY col6 DESC ``` Or, do you want to just pull the first row with the latest date (r...
SQL Group Data Issue
[ "", "sql", "grouping", "" ]
new to SQL (Searched my problem but couldn't find anything :() I'm hoping this is something simple... Basically I'm trying to query a simple table of real estate properties which have Price, Address etc as well as Property Type (Detached, Semi, Apartment). I'm asked to return the Highest and Lowest priced property for ...
The problem that you have is that you are comparing to the lowest/largest prices for all property types. So, property type 1 could match the lowest price of property type 2, and it will be in your output. You want correlated subqueries: ``` SELECT Area, Address, Property_Code, Property_Type, Price, Market_Date, Sold ...
If you just need a list of property types and then the lowest sale price and highest sales price for each then try the following: ``` SELECT Property_Type, MIN(Price) AS LowestPrice, MAX(Price) AS HighestPrice FROM tbl_Sale_Property AS sp GROUP BY Property_Type ```
Nested SQL query using min/max is returning too many records (New to this)
[ "", "sql", "max", "min", "" ]
I have a mysql\_query . I was wondering which one to index. ``` SELECT count(*) FROM foo WHERE c=5 GROUP BY d ``` Maybe (c,d) or just c? I have another similar. ``` SELECT count(*) FROM foo WHERE d=6 GROUP BY b ``` Maybe (d,b) or just d? Another one here : ``` SELECT a FROM foo WHERE b=5 GROUP BY c ``` Here (a,...
It's impossible to have one index to cover all use case. MySQL can benefit from having index on order by/ group by columns. Saves it from doing filesort, temporary tables. My suggestions would be: 1) (c,d) 2) (d,b) 3) For the last one (a,b,c) would be unusable because it starts with a (column order matters). The pr...
For these three queries, you need three different indexes, one on `a`, one on `b`, and one on `c`. These can be composite indexes, so they could be `a,b,c`, 'b,c,a`', and`c,b,a`. But for each query, you need an index that has the one column in the`where` clause as the first column in the index. MySQL uses the columns ...
Indexing columns in mysql
[ "", "mysql", "sql", "database", "indexing", "" ]
I defined a function to always give me the date of the next Sunday. It works fine, here is the code: ``` CREATE FUNCTION nextSunday() RETURNS date AS $$ DECLARE dia_semana INT := CAST(EXTRACT(DOW FROM CURRENT_DATE)as INT); dia INT := 7 - dia_semana; BEGIN RETURN current_date + dia; END; $$ LANGUAGE plpgsq...
First of all, your function can be much simpler with [**`date_trunc()`**](https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC): ``` CREATE FUNCTION next_sunday() RETURNS date LANGUAGE sql STABLE PARALLEL SAFE AS $func$ SELECT date_trunc('week', LOCALTIMESTAMP)::date + 6; $func$...
In my case, I was calling directly function fun1 from another function like: ``` CREATE OR REPLACE FUNCTION fun2() returns trigger LANGUAGE plpgsql VOLATILE AS $BODY$ BEGIN raise notice 'trigger fun2 with id: %', new.id; fun1(new.id); return trigger; END; $BODY$; ``` Resolved issue by calling function ...
Calling a function inside another function in PL/pgSQL
[ "", "sql", "postgresql", "date", "plpgsql", "" ]
There are 3 tables: ``` Users table ------------ |uid|username| ------------ Values table ------------------ |vid|values|checked| ------------------ Relations ----------- |cid|uid|vid| ----------- ``` Relations table contains user ids related to value ids. How to select value id from values table that...
I think you can execute a simple query like this (assuming that the data type of user identifier is `int`): ``` DECLARE @givenUserID int --local variable where you store the given user identifier SELECT vid FROM Values WHERE vid NOT IN (SELECT vid FROM Relations where uid = @givenUserID) ```
Which dbms are you using? Does it support the minus clause? If yes you can do something like this ``` select vid from values minus select vid from relations where uid = @user_id ``` this should give the vid's which are not mapped to a given user id Another way to do this is through a not-exists clause (...
SQL query from 3 different tables
[ "", "mysql", "sql", "" ]
I have a query, shown below. However when I run this query I get rows whose [date\_effective] is prior to 14th Feb 2014. Why? I have dates of 1/1/1980 showing up. ``` SELECT * FROM D_CORPACTIONS_MSCI WHERE [date_effective] >= '14 February 2014' AND [ca_status] = 'EXPECTED' OR [ca_status] = 'CONF...
Your `and` and `or` are conflicting each other. Therefore the matched rows aren't correct. Try to encapsulate the `or` statements or, it this case, use an `in`: ``` select * from d_corpactions_msci where date_effective >= '14 february 2014' and ca_status in ('EXPECTED', 'CONFIRMED', 'UNDETERMINED') order by ...
``` SELECT * FROM d_corpactions_msci WHERE ( date_effective >= '14 February 2014' ) AND ( ca_status = 'EXPECTED' OR ca_status = 'CONFIRMED' OR ca_status = 'UNDETERMINED' ) ORDER BY date_effective ```
Sql Server Date Query not working
[ "", "sql", "sql-server", "t-sql", "" ]
I have the following query: ``` SELECT SUM (T0.[TotalSumSy]) AS 'Line Sterling', T0.[WhsCode] AS 'Business Unit' FROM [dbo].[INV1] T0 INNER JOIN [dbo].[OINV] T1 ON T1.[DocEntry] = T0.[DocEntry] WHERE T1.[DocDate] > (CONVERT(DATETIME, '20121001', 112) ) GROUP BY T0.[WhsC...
There is another option for doing this query, which is to do the aggregation only once. ``` select sum("Line Sterling") as [Line Sterling], [Business Unit] from ((SELECT T0.[TotalSumSy] AS [Line Sterling], T0.[WhsCode] AS [Business Unit], t1.DocDate FROM [dbo].[INV1] T0 INNER JOIN [dbo].[OINV] T1 ...
Try something like : ``` select sum([TotalSumSy]), WhsCode AS 'Business Unit' from ( SELECT TotalSumSy, T0.[WhsCode] FROM [dbo].[RIN1] T0 INNER JOIN [dbo].[ORIN] T1 ON T1.[DocEntry] = T0.[DocEntry] WHERE T1.[DocDate] > (CONVERT(DATETIME, '20121001', 112) ) UNION ALL SELECT T0.[TotalSumSy]*-1, T0.[W...
SQL Server 2008r2 Union All Group By
[ "", "sql", "sql-server-2008", "" ]
In MySQL query: ``` SELECT host FROM information_schema.processlist WHERE ID = connection_id( ) LIMIT 0 , 30 ``` The result of ^ this query is: `localhost`. ``` SELECT @@hostname; ``` The result of ^ this query is: `localhost`. But I need to get ipaddress like `192.168.1.2`. **Question:** *How to get this result ...
To get the IP address only without the port number. ``` Select SUBSTRING_INDEX(host,':',1) as 'ip' From information_schema.processlist WHERE ID=connection_id(); ```
The query `select host from information_schema.processlist WHERE ID=connection_id();` Will give you the host name .You will get IP address( like `192.168.1.2.`) if name resolution is not enabled, which it is usually not.
Getting ip address using MySQL query
[ "", "mysql", "sql", "ip-address", "" ]
I am using MySQL. I am trying to compare a date that is in a datetime field to today's date and return the number of days difference [i.e. today - column = no. of days] Is that possible? How would I do it?
I think we need more information from your side, like the query you are using and what you tried so far, but maybe this can help you out: ``` SELECT DATEDIFF('2014-02-20 00:00:00', NOW()); //return 7 ``` In this case, you should add a 'FROM table' and replace the date in this query to the `datetime` column. Some...
You can try to use DATEDIFF function ``` SELECT DATEDIFF(NOW(), date_column) ``` It should return the number of days between now and your column.
Compare date to today's date and return number of days
[ "", "mysql", "sql", "datetime", "" ]
In SQL Server 2012, I have a 'cross-reference' table containing four columns. The combination of the four columns must be unique. My initial thought was to simply create a a primary key containing all four columns, but some research has suggested that this might not be a good idea. **Background to question...** I am t...
Having a multi column primary key should do the trick ``` CREATE TABLE TagList ( TagId nvarchar(40) NOT NULL, ReferenceGuid uniqueidentifier NOT NULL, ReferenceId int NOT NULL, ObjectType nvarchar(40) NOT NULL, CONSTRAINT pk_TagList PRIMARY KEY (TagId,Reference...
If you only require a unique constraint, and not a primary key, this can be used: ``` ALTER TABLE TagList ADD CONSTRAINT UK_TagList_1 UNIQUE ( TagId, ReferenceGuid, ReferenceId, ObjectType ) ```
How do I enforce uniqueness against four columns
[ "", "sql", "sql-server", "tags", "indexing", "" ]
I am trying to update a field in a table using an SQL update query where there is a like statement referencing a value in another table. They syntax unfortunately is not working. Below is my code. In short, I am trying to put a '1' in the field 'Query07ParolaChiave' in the table 'tblSearchEngine01' when the value locat...
I suggest you 2 solutions : This one is using `EXISTS` functions, and will check for each row in `tblSearchEngine01` if there is a matching value in `tblsearchengine07` ``` UPDATE tblSearchEngine01 SET tblSearchEngine01.Query07ParolaChiaveSelect = '1' WHERE EXISTS (SELECT 1 FROM tblsearch...
The like statement go into the WHERE clause. If you do want to use LIKE without you care about caps letters, then you can use it like this: LIKE COLUMN\_NAME = '%WhatYouLike%'
How do I run an SQL update query using a like statement
[ "", "sql", "vba", "ms-access", "ms-access-2010", "" ]
I have the following 2 tables: ``` CREATE TABLE `personal_info` ( `p_id` int(11) NOT NULL AUTO_INCREMENT, `name` text NOT NULL, `initials` text NOT NULL, `surname` text NOT NULL, `home_lang` int(11) NOT NULL, PRIMARY KEY (`p_id`), KEY `home_lang` (`home_lang`), CONSTRAINT `personal_info_ibfk_1` FOREIGN KEY (`h...
Your `DROP FOREIGN KEY` syntax is using the wrong key name. It's trying to drop your "plain" index on the `home_lang` field. It's NOT the foreign key itself. ``` CONSTRAINT `personal_info_ibfk_1` FOREIGN KEY (`home_lang`) REFERENCES `language_list` (`ll_id`) ^^^^^^^^^^^^^^^^^^^^^--- THIS is the name of the...
Use this given below query to find the name of the foreign key. ``` SHOW CREATE TABLE forms_main; ``` Then once u got the key, execute drop foreign key command ``` alter TABLE `forms_main` drop FOREIGN key `forms_main_ibfk_1`; ``` Then execute the drop column command ``` ALTER TABLE `forms_main` DROP `company_id`;...
Drop Column with foreign key in MySQL
[ "", "mysql", "sql", "database", "database-design", "" ]
I'm trying to filter out my (users table) data with conditions derived from data in (users\_status table). The **users** table is a table containing user ids and usernames ``` CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(25), PRIMARY KEY (`id`) ) ENGINE=InnoDB; ``` ...
The following assumes that a user can have different bookmark status for different groups at the same time. It finds the most recent date for each (user\_id, group\_id) combination, then finds the record that corresponds to that. Either the bookmark needs to be `'off'` or `NULL` as dictated by the `WHERE` clause. It...
1- you using `group by` before `WHERE` clause 2- you are grouping by two columns in subquery while you should group by one columns try this working query ``` select us.id, us.group_id, g.name as GROUP_NAME, us.user_id, u.username as USER_USERNAME, us.bookmarked, us.date from user_status us inner join users u ON u.i...
group by and count within a subquery
[ "", "mysql", "sql", "subquery", "" ]
This is my query which I want to insert the value which should be selected from another table: ``` insert into payment_details_kohin(installment_no) values( select count(installment_amount)+2 from kohin_plan.payment_details_insert where customer_id='KBP100058' ) ``` …but its gives me an error: > Msg 515, Level 1...
Your problem is that you have a non-NULL customer id. You need to insert it into the table as well: ``` insert into payment_details_kohin(customer_id, installment_no) select customer_id, count(installment_amount)+2 from kohin_plan.payment_details_insert where customer_id='KBP100058'; ``` However, when ...
You dont need the Values clause here just do as follows ``` INSERT INTO payment_details_kohin(installment_no) SELECT ISNULL(COUNT(installment_amount), 0) + 2 FROM kohin_plan.payment_details_insert WHERE customer_id = 'KBP100058' ```
Insert into and select combination is not working
[ "", "sql", "sql-server-2008", "" ]
I have a table which contains different messages, each with a messageType field. I need to fill a ASP.NET list control of the last loaded message for each messageType. My sql statement to return everything is: ``` SELECT MessageTypes.MessageType MessageType ,Messages.MessageDate ,Messages.ValueDate ,Messag...
You can use the [ROW\_NUMBER()](http://technet.microsoft.com/en-us/library/ms186734.aspx) Function to assign each of your messages a rank by Message date (starting at 1 again for each message type), then just limit the results to the top ranked message: ``` WITH AllMessages AS ( SELECT MessageTypes.MessageType, ...
Try this: ``` SELECT MT.MessageType ,X.MessageDate ,X.ValueDate ,X.MessageReference ,X.Beneficiary ,X.StatusId ,X.STATUS ,X.BIC FROM MessageTypes MT OUTER APPLY -- or CROSS APPLY ( SELECT TOP 1 M.MessageDate ,M.ValueDate ,M.MessageReference ,M.Beneficiary ,M.StatusId ...
Get Last message loaded based on message type
[ "", "sql", "t-sql", "" ]
I'm creating a database-backed calendar in RoR, and the first step of this is to return all events that fall within a given year. My events table schema is as follows: ``` id:integer description:string startdate:datetime enddate:datetime ``` In English, I think this is the logic I need to execute to return all events...
write a scope in your model ``` class Event < ActiveRecord::Base scope :event_in_year, lambda { |year| where('(events.startdate < ? AND events.enddate > ? ) OR (events.startdate > ? AND events.enddate < ? ) OR (events.startdate < ? AND events.enddate > ? )', year.beginning_of_year, year.beginning_of_year, year.b...
With `ActiveRecord` `where` method, you can pass a `string` query to suit your needs. So something like: ``` your_string = "events.start_date > ...." Model.where(your_string) ```
Execute OR and AND conditionals with ActiveRecord helpers
[ "", "sql", "ruby-on-rails", "" ]
I have inserted records into a SQL Server database table. The table had a primary key defined and the auto increment identity seed is set to “Yes”. This is done primarily because in SQL Azure, each table has to have a primary key and identity defined. But since I have to delete some records from the table, the identit...
The [`DBCC CHECKIDENT`](http://technet.microsoft.com/en-us/library/ms176057.aspx) management command is used to reset identity counter. The command syntax is: ``` DBCC CHECKIDENT (table_name [, { NORESEED | { RESEED [, new_reseed_value ]}}]) [ WITH NO_INFOMSGS ] ``` Example: ``` DBCC CHECKIDENT ('[TestTable]', RESEE...
``` DBCC CHECKIDENT ('TestTable', RESEED, 0) GO ``` Where 0 is `identity` Start value
Reset identity seed after deleting records in SQL Server
[ "", "sql", "sql-server", "database", "sql-server-2008", "azure-sql-database", "" ]
I have this table: ``` ID Name 01 02 03 04 05 06 07 0000068 Name1 V VX 0000069 Name2 V VX VX V V 0000070 Name3 V V V V V V ``` This is an table for absence check and I want to count the amount of data from each row from column 01 t...
If the number of columns is static, you can use a simple `CASE` expression. ``` SELECT *, CASE WHEN [01] = '' OR [01] IS NULL THEN 0 ELSE 1 END + CASE WHEN [02] = '' OR [02] IS NULL THEN 0 ELSE 1 END + CASE WHEN [03] = '' OR [03] IS NULL THEN 0 ELSE 1 END + CASE WHEN [04] = '' OR [04] IS NULL THEN 0 ELSE 1 END + ...
If it's always `V` or `VX` you could replace the `VX` with `V`, concatenate them together and take the `LEN()`: ``` SELECT *, LEN(REPLACE([01]+[02]+[03]+[04]+[05]+[06]+[07],'X','')) AS New_Ct FROM YourTable ``` If the blanks are actually `NULL` you'd have to wrap them in `ISNULL()`: ``` SELECT *, LEN(REPLACE(ISNULL(...
How to count amount of data for each row
[ "", "sql", "sql-server-2008", "" ]
This question relates to the answer given in [this post](https://stackoverflow.com/a/21804334/1688265). I want to convert the output from a tree analysis in Weka into a hierarchical table of decision splits and leaf-values (as per the post linked above). I can parse the Weka output to extract the `fac`, `split` and `v...
As you noted, each of your Weka output lines corresponds to 0, 1, or 2 INSERT statements. I'm restating some of what you said in case it helps you or someone else reading. **Summary** Output lines with < and without . are pure branch nodes (IFs) and correspond to 1 `INSERT` with null for the column [val]. Output lin...
Here's SQL code that may work to turn your Weka output into the rows for the [decisions] table. Obviously, SQL isn't the natural language to use, but it's what I had open and handy near the rest of the SQL for this question. Ultimately, they key idea is to implement a stack to keep track of the hierarchy. This is terr...
Convert Weka tree into hierachyid for SQL hierachical table
[ "", "sql", "sql-server", "parsing", "weka", "decision-tree", "" ]
I have the following SQL query that is returning a result of `92.967013425802` and I need it to be formatted like `93%` and add the percent sign. I have tried changing the sum to round but I received an error > The function 'round' is not a valid windowing function, and cannot be used with the OVER clause. My query: ...
``` select --Cast(Round(count(*) * 100.0 / sum(count(*)), 0) as nvarchar(5) + '%' CAST(Round(count(*) * 100.0 / sum(count(*)), 0) as nvarchar(5)) + '%' from db_table_MetaData ``` This should do the trick. In essence you take the 08/15 `ROUND()` function to get your numeric value. After this you cast ...
Strange you got not a valid function. Perhaps you didn't provide the correct parameters? This worked for me. ``` select cast(Round('92.967013425802', 0) as nvarchar(10)) + '%' ```
SQL Server : round and add percent sign
[ "", "sql", "sql-server", "sql-server-2008", "" ]
My apologies. I have edited the below into 2 table, Im just having a bit of confusion. --- I have a tables very similar as the ones below and I wanted to show all the table2-class 1 but only 1 random item per each table1-category Sample Item Table1 ``` +---------+---------------+---------------+ | ID | Item ...
You can do something like this ``` SELECT t.id, itemname, category FROM ( SELECT ( SELECT id FROM table1 WHERE category = t.category ORDER BY RAND() LIMIT 1 ) id FROM table1 t GROUP BY category ) q JOIN table1 t ON q.id = t.id ``` Note: *using `RAND()` is very costly* Out...
Try something like this: ``` SELECT id, itemname, category FROM ( SELECT id, itemname, category FROM sample_table ORDER BY RAND() ) AS tmp GROUP BY category ``` Note that this query is totally valid in MySQL <http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html>
MySQL - Selecting single entry per category
[ "", "mysql", "sql", "" ]
Im in my final stages of creating a database for my android app, however, I cannot seem to get my primary key to increment. Here is my code where I set it up, ``` public class DatabaseHandler extends SQLiteOpenHelper { // All Static variables // Database Version private static final int DATABASE_VERSION =...
To make the database auto-generate the primary key for you, just don't specify it yourself. Remove this line from the insert code: ``` values.put(KEY_P, journey.getpKey()); ``` You can capture the generated id from the return value of [`insert()`](http://developer.android.com/reference/android/database/sqlite/SQLiteD...
*Go through the following steps* **Modify your Creating Tables code like this** ``` // Creating Tables @Override public void onCreate(SQLiteDatabase db) { String CREATE_JOURNEY_TABLE = "CREATE TABLE " + TABLE_JOURNEY + "(" + KEY_P + " INTEGER PRIMARY KEY AUTOINCREMENT DEFAULT 1 ," + KEY_ID + " TEXT," ...
Android SQLite - Primary Key - Inserting into table
[ "", "android", "sql", "sqlite", "" ]
I'm very new to this so I will try to explain this as good as I can, also try to explain as basic as you can, thank you! I have a list with bills that a company gets when they buy something, I'm trying to select only those that have NOT bought anything (therefore their CustomerID is not on the Bill-list). How do I do ...
Meanwhile i prefer `NOT EXISTS` since it's more readable, maintainable and has no issues with null-values: ``` SELECT Name, Postnr + ' ' + City AS Postadress FROM Customer c WHERE NOT EXISTS (SELECT 1 FROM bill b WHERE b.CustomerID = c.CustomerID) ``` Another (possibly less efficie...
You explained it quite well. You should have made your SQL right from your explanation: Customer with their CustomerID not in Bill list. Now this would be like: ``` select * from Customer where CustomerID not in (select CustomerID from Bill) ``` Dependent on your database system the syntax could vary slightly e.g. no...
Selecting those that does not match
[ "", "sql", "sql-server", "join", "" ]
I have a simple tree that has 4 level of deep data. Here is the table DDL ``` CREATE TABLE HIER_DEMO( ID NUMBER, LABEL VARCHAR2 (100), PARENT_ID NUMBER) ``` Hierarchy starts `WITH ID = PARENT_ID`. Number of levels are fixed. It is always 4. We have leafs to all branches at 4th level. So we can als...
``` SQL> select * from HIER_DEMO 2 start with label like '%Brian%' 3 connect by prior id = parent_id 4 union 5 select * from HIER_DEMO 6 start with label like '%Brian%' 7 connect by prior parent_id = id and PRIOR parent_id != PRIOR id 8 / ID LABEL PARENT_ID ...
We can use recursive CTE to accomplish this ``` WITH CTE1(ID, LABEL,PARENT_ID) AS ( SELECT * FROM Hier_Demo WHERE LABEL LIKE '%Brian%' UNION ALL SELECT h.ID, h.LABEL, h.PARENT_ID FROM Hier_Demo h INNER JOIN CTE1 c ON h.ID = c.PARENT_ID WHERE h.ID <> h.PARENT_ID ), CTE2(ID, LABEL,PARENT...
SQL query for searching in the tree
[ "", "sql", "oracle", "search", "tree", "" ]
I read a **45-tips-database-performance-tips-for-developers** document from a famous commercial vendor for SQL tools today and there was one tip that confuse me: > If possible, avoid NULL values in your database. If not, use the > appropriate IS NULL and IS NOT NULL code. I like having NULL values because to me it is...
The NULL question is not simple... Every professional has a personal opinion about it. Relational theory Two-Valued Logic (2VL: TRUE and FALSE) rejects NULL, and Chris Date is one of the most enemies of NULLs. But Ted Codd, instead, accepted Three-Valued Logic too (TRUE, FALSE and UNKNOWN). Just a few things to note ...
Besides the reasons mentioned in other answers, we can look at NULLs from a different angle. Regarding duplicate rows, Codd said > If something is true, saying it twice doesn’t make it any more true. Similarly, you can say **If something is not known, saying it is unknown doesn't make it known.** Databases are use...
Why should I avoid NULL values in a SQL database?
[ "", "sql", "database-design", "" ]
I have following tables: **Table 1 : `AccessMenu`** ``` userid item 1 a 2 b 2 c ``` and **Table 2 : `ActionRights`** ``` idAdmin itemCol 2 v 2 m 2 d ``` **DESIRED RESULT:** ``` userid yes/no 1 no 2 yes ``` When I ge...
``` SELECT userid, CASE WHEN idadmin IS NULL THEN 'No' ELSE 'Yes' END AS 'Grp' FROM (SELECT accessmenu.userid AS UserId, actionrights.idadmin AS IdAdmin FROM accessmenu LEFT JOIN actionrights ON actionrights.idad...
Please check using subquery: ``` select distinct userid, case when (SELECT COUNT(*) from ActionRights b where b.idAdmin=a.userid)>0 then 'Yes' else 'No' end [Yes/No] from AccessMenu a ```
How do I check if a table have matching record in another table?
[ "", "sql", "database", "sql-server-2008-r2", "" ]
I have a `select` statement ``` SELECT * FROM TABLENAME WHERE WORKERNAME = 'A' AND DATE = '12/17/2014' ``` The output will be: ``` FREE | USED | DATE | WORKERNAME ------------------------------------ 1 | 0 |12/17/2014 | A 1 | 0 |12/17/2014 | A 1 | 0 |12/17/2014 | A ``` I need to...
It would not be that elegant to produce the output you are after using pure SQL or even PL/SQL. It would be better if you let a client do the work. Depending on how you want to present your final output to an end user your choices are ranging from simple SQL\*PLUS to a more sophisticated reporting tools. Here is a simp...
``` TTITLE LEFT 'Manager: ' MGRVAR SKIP 2 BREAK ON MANAGER_ID SKIP PAGE BTITLE OFF SELECT MANAGER_ID, DEPARTMENT_ID, LAST_NAME, SALARY FROM EMP_DETAILS_VIEW WHERE MANAGER_ID IN (101, 201) ORDER BY MANAGER_ID, DEPARTMENT_ID; Manager: 101 DEPARTMENT_ID LAST_NAME SALARY ------------- -------...
Display row values as column header
[ "", "sql", "oracle", "plsql", "oracle10g", "" ]
I'm performing a query on a table which tracks the results of a test taken by students. The test is composed of multiple sections, and there is a column for each section score. Each row is an instance of the test taken by a student. The sections can either be taken all at once, or split into multiple attempts. For exam...
Sorry - my previous answer answered a DIFFERENT question than the one posed :) It will return all data from the MOST RECENT row. The question asked is to aggregate over all rows to grab the most recent score for each subject individually. But I'm leaving it up there because the question I answered is a common one, and...
This is tricky. Each section score is coming potentially from a different record. But the normal rules of `max()` and `min()` don't apply. The following query gets a sequence number for each section, starting with the latest non-NULL value. This is then used for conditional aggregation in the outer query: ``` select ...
Group By Column, Select Most Recent Value
[ "", "sql", "t-sql", "" ]
I can not find out what is wrong with my SQL Query: ``` CREATE TABLE Product ( productID int NOT NULL, name varchar(255) NOT NULL, price int(255), PRIMARY KEY (productID) ) CREATE TABLE User ( ...
There are some syntax error in your `create table` statement. * **Date** is a keyword so not a good practice to use it. * **User\_id** is **int** in your `USER` table and in `purchased` table you are making it **varchar** * For **date datatype** no need to specify the **number of characters.** The correct statement i...
To start with, you have a syntax error in your third `CREATE TABLE` statement, where you have specified a comma before `NOT NULL` constraint and a missing comma before second foreign key definition. Another thing to note is, you are not supposed to specify any parameter to `DATE` data type, like you have specified. E...
SQL Structure help and query
[ "", "mysql", "sql", "database", "" ]
I would like to know if the last character of a string is an asterisk `*` I have got the following which gives me the last character: ``` select RIGHT('hello*',1) ``` but how would I use it as a condition in an if statement by matching it? the following doesn't work as it only returns the last char. ``` select '*' ...
You're just about there. By using: ``` select '*' = RIGHT('hello*',1) ``` Sql evaluates the `RIGHT` but thinks you want to alias it as a column named `*` You can use the expression conditionally: ``` if RIGHT('hello*',1) = '*' print 'Ends in *' else print 'Does not end in *' ``` You can filter like so on ...
StuartLC mentioned performance. You can performance gains at the cost of an indexed persisted computed column. This tactic has been mentioned several in other places, such as: * [sql-server-index-columns-used-in-like](https://stackoverflow.com/questions/1388059/sql-server-index-columns-used-in-like) * [sql-server-inde...
how to match last character of string in TSQL?
[ "", "sql", "t-sql", "" ]
I have this table that has wide range of dates and a corresponding value for each one of those dates, an example shown below. ``` Date Value 6/01/2013 8 6/02/2013 4 6/03/2013 1 6/04/2013 7 6/05/2013 1 6/06/2013 1 6/07/2013 3 6/08/2013 8 6/09/2013 4 6/10/2013 2 ...
Using `data.table` ``` require(data.table) #Build some sample data data <- data.table(Date=1:20,Value=rpois(20,10)) #Build reference table Ref <- data[,list(Compare_Value=list(I(Value)),Compare_Date=list(I(Date)))] #Use lapply to get last seven days of value by id data[,Roll.Val := lapply(Date, function(x) { ...
`zoo` has a function `rollapply` which can do what you need: ``` z <- zoo(x$Value, order.by=x$Date) rollapply(z, width = 7, FUN = sum, partial = TRUE, align = "right") ## 2013-06-01 8 ## 2013-06-02 ...
Moving sum over date range
[ "", "sql", "r", "count", "sum", "data.table", "" ]
I was solving one of the puzzles and came across swapping column values using DML queries: ``` SELECT * FROM TEMP_TABLE; ID1, ID2 -------- 20, 15 20, 15 20, 15 ``` Solution is mathematical calculation: ``` UPDATE TEMP_TABLE SET ID1=ID1+ID2; UPDATE TEMP_TABLE SET ID2=ID1-ID2; UPDATE TEMP_TABLE SET ID1=ID1-ID2; ``` N...
There's no need to have three update statements, one is sufficient: ``` UPDATE temp_table_new SET id1 = id2, id2 = id1; ```
``` CREATE TABLE Names ( F_NAME VARCHAR(22), L_NAME VARCHAR(22) ); INSERT INTO Names VALUES('Ashutosh', 'Singh'),('Anshuman','Singh'),('Manu', 'Singh'); UPDATE Names N1 , Names N2 SET N1.F_NAME = N2.L_NAME , N1.L_NAME = N2.F_NAME WHERE N1.F_NAME = N2.F_NAME; SELECT * FROM Names; ```
Swapping column values in Oracle
[ "", "sql", "oracle", "logic", "" ]
I don't want a temporary join, I want to actually update one column to be the equivalent of its counterpart from another table based on sharing an ID. It would be something like this: ``` UPDATE parts2.PartNumber SET parts2.PartNumber=parts.PartNumber WHERE parts2.id=parts.id; ``` Thanks in advance, sorry if this i...
I believe the following will give you the desired results. But it based on a join: ``` UPDATE parts2, parts SET parts2.PartNumber=parts.PartNumber WHERE parts2.id=parts.id; ``` It will do exactly what you want. And it is a most efficient way. I don't see any sence in trying to avoid `JOIN` here
You can do this by joining **parts** and **parts2** table . ``` UPDATE parts2 AS p2 INNER JOIN parts AS p1 ON p1.id= p2.id SET p2.PartNumber=p1.PartNumber ```
Merge single column of one table into another based on ID
[ "", "mysql", "sql", "" ]
I have a column which has values of format "01-01-2012" and I need to change it to "01.01.2012". I have to do the same for all the entries of that coloumn. Could you please suggest a way to do it? I need a general SQL statement. Thanks
Try this using [REPLACE](http://dev.mysql.com/doc/refman/5.5/en/replace.html): ``` update tablename set column_name=REPLACE(column_name,'-','.') ```
One way to do this would be to use a basic `UPDATE` statement. In this case, you would update your entire table and for each row, set the value of the column to the formatted value. The basic outline would be like so: ``` UPDATE [TableName] SET [ColumnName] = [FormattingExpression] ``` An example of [FormattingExp...
Format values on entire column SQL
[ "", "mysql", "sql", "date-format", "" ]
I have a MySQL database show uptime for devices. The uptime is how long the device has been up in seconds. I have a query showing all devices with uptime less than 86400 (24 hours) which I want to bring into a PHP page. I want to format this uptime string number into a datetime that's human readable. Here is my query:...
``` SELECT NOW() - INTERVAL 10329 SECOND ```
`TIME_FORMAT(SEC_TO_TIME(uptime),'%Hh %im')` Google: [Convert seconds to human readable time duration](https://stackoverflow.com/questions/8193868/convert-seconds-to-human-readable-time-duration) `select hostname,type,TIME_FORMAT(SEC_TO_TIME(uptime),'%Hh %im') from devices where uptime < 86400` This will give you Ho...
MySQL: Convert relative seconds count to datetime?
[ "", "mysql", "sql", "datetime", "" ]
I have two tables, with independent ids (can't be connected via joins), I want to query and get a GROUP\_CONCAT of both columns. Example: table "a" has ids: **1, 2, 3**. table "b" has the ids: **10, 11**. End result should be: **1, 2, 3, 10, 11** I have tried a few queries: ``` SELECT CONCAT_WS(',', GROUP_CONCAT(a....
Try `union all`: ``` select group_concat(ab.id) as ids from ((select id from a ) union all (select id from b ) ) ab; ``` Your queries are doing cross join's between the tables, so data after the cross join is: ``` a.id b.id 1 10 1 11 2 10 2 11...
`GROUP_CONCAT(DISTINCT [])` will help <https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat>
GROUP_CONCAT on two tables
[ "", "mysql", "sql", "concatenation", "" ]
I need to show some records sorted based on modified column (latest activity on top) (Post with new edit or comments at the top) App UI has twitter like 'more' post button for infinite scroll. each 'more' will add next 10 records to UI. Issue is that pagination index breaks when any of the to be shown record is modif...
I would do a NOT IN() and a LIMIT instead of just a straight LIMIT with a pre-set offset. ``` SELECT * FROM Jobs WHERE name NOT IN('A','B','C','D','E','F','G','H','I','J') ORDER BY last_modified DESC LIMIT 10 ``` This way you still get the most recent 10 every time but you would need to be tracking what IDs have alr...
Twitter timelines not paged queries they are queried by ids This page will help you a lot understanding timeline basics <https://dev.twitter.com/docs/working-with-timelines> lets say each column have id field too ``` id msg 1 A 2 B .... ``` First query will give you 10 post and max post\_id will be 10 Next query...
Pagination issue while sorting based on last modified property
[ "", "mysql", "sql", "sql-server", "postgresql", "pagination", "" ]
This is my table ``` +---------------------+ | access_time | +---------------------+ | 2014-02-17 12:00:00 | | 2014-02-15 12:00:00 | | 2014-02-15 12:00:00 | | 2014-02-15 12:00:00 | | 2014-02-15 11:00:00 | | 2014-02-14 02:00:00 | | 2014-02-13 18:00:00 | | 2014-02-13 12:50:05 | | 2014-02-13 12:48:57 | | 2014-02-...
If you want one arbitrary time per day, you can do: ``` select access_time from table t group by date(access_time); ``` More typically,you would choose which of the times you would want, and do something like: ``` select min(access_time) from table t group by date(access_time); ```
For SQL Server 2008 or more recent versions, I'd recommend: ``` select cast(access_time as date) from t group by cast(access_time as date) ```
How to select distinct days, excluding time of that day
[ "", "mysql", "sql", "sql-server", "" ]
I have a `Date` column in SQL (of **DateTime** datatype). For a particular scenario, I need to show it as blank in my browser. I tried ``` Dim DOB As Nullable(Of Date) = Date.Now Dim datestring As String = DOB.Value.ToString("d") DOB = Nothing ``` But it gives me error saying `DateTime was not in a proper format`. W...
You can try either of the following: ``` Dim datestring As String = IF(DOB Is Nothing,"", DOB.Value.ToString("d")) ``` or ``` Dim datestring As String = "" If Not DoB Is Nothing Then datestring = DOB.Value.ToString("d") End If ```
The reason why your code would throw `DateTime was not in a proper format` is because *most likely* you don't do `Dim DOB As Nullable(Of Date) = Date.Now`. You get date from database and then go straight for value and value is null. Let's say you have a Sql table with nullable date field and you read it using DataRead...
Set SQL DateTime to Empty/Nothing in vb.net
[ "", "sql", "vb.net", "datetime", "null", "" ]
I have a schema called `GBO_ARC_SCHEMA`, in which I have one table called `TEST_EMP`, and I have two users say `USER_A` and `USER_B`. First I connected to `USER_A` and fired below query ``` select count(*)from TEST_EMP; count ----- 20 ``` After that I connected as `USER_b` and fired below query but it is giving an ...
If you want *all* users to be able to select from the table without qualifying with the schema name, you want to create a *public synonym*: ``` create public synonym TEST_EMP for GBO_ARC_SCHEMA.TEST_EMP; ``` If you only want `user_b` to omit the schema name, you want to create a *private synonym* WITHIN user\_b's sch...
On the server roles for the login you are using, simply uncheck sysadmin and serveradmin roles. That should solve it
Accessing a table without specifying the schema name
[ "", "sql", "oracle", "plsql", "oracle11g", "oracle-sqldeveloper", "" ]
I have a table which stores ID's in a comma separated string as follows: ``` field_id_13 ------------ 1234,5266,3678,4733,7372,5766,2578 ``` and I'm using the following Active Record Construct (CI), to pull out the data: ``` $this->db->select("*") ->from("channel_data d") ->join("channel_titles t","t.entry_i...
You have to use FIND\_IN\_SET in where condition ``` $this->db->where("FIND_IN_SET('$id',d.field_id_13 ) !=", 0); ```
The simplest way, if not the most elegant, would be to add commas to the start and end of the values in the id field, and then search for the value surrounded by commas as well. In other words: ``` field_id_13 ------------ ,1234,5266,3678,4733,7372,5766,2578, ``` and: ``` $this->db->select("*") ->from("channel_d...
Using LIKE to pull out an ID from comma separated string
[ "", "mysql", "sql", "codeigniter", "sql-like", "" ]
I am creating a database of school gradebook. I have 2 tables: Class and Teacher. And i have a problem. A teacher needs to be a form-master of class. How should i make this relationship? **Variant 1:** **Class** will have a **teacherId** property. **Variant 2:** **Teacher** will have a **classId** property. What var...
*3 types of relationships are possible, generally speaking:* **One-to-many** * If a class can have many teachers, but a teacher can only teach one class, then put `ClassID` on the Teacher table. **Many-to-many** * If a class can have many teachers, and a teacher can teach many classes, then make a 3rd table, `Teach...
Making the assumption that a specific class is taught by one teacher and that a teacher can typically teach more than one class you will want to add a TeacherId to the class entity.
About Database development, what variant is better?
[ "", "sql", "" ]
I don't know how else to call this. I have this table right here: ![phpMyAdmin screenshot](https://i.stack.imgur.com/gayvK.jpg) And as you can see `Titon` followed `SLH_444` and `Knoedel_475`. Now, how can I select all rows for users whom `Titon` followed? I expect a result of all rows where the `username` is either...
I think you want: ``` SELECT * FROM ACTIVITIES WHERE username in (select targetname from ACTIVITIES where activity='followed' and username='Titon'); ``` Although Titon has not followed `SLH_444`, he has followed `SLB_444`.
``` SELECT targetname FROM ACTIVITIES WHERE username = 'Titon' AND activity = 'followed'; ```
How to select with multiple subqueries?
[ "", "sql", "" ]
I am loading data from a sqlite database into a ms SQL database. The field type in the Sqlite is Numeric. What is the best field type to use so that I don't loose any detail?
What is the underlying data representing? `Numeric` in SQLite is a technically a column affinity and not a storage type. Other databases do not have the concept of "column affinity", which is explained [here](http://www.sqlite.org/datatype3.html). In SQL Server, the types describe how the data is being stored. The int...
My understanding of SQLite is limited, but from what I'm reading here: [Datatypes in SQLite](http://www.sqlite.org/datatype3.html), the numeric affinity does not seem to actually tell you much about the data contained therein. If that's the case, the best thing to do is to query the values to see what you're dealing w...
What is the best SQL field type to use for a Sqlite numeric
[ "", "sql", "sql-server", "sqlite", "" ]
I have a feeling this is a fairly simple one. I need to edit a line in the `SELECT` statement that looks to see if there is a value of `NULL` in a field. If there is a `NULL` value, I need the new column (not named) to display a '0' for that row. Where the row has data I need to display '1' in that row. Is there a way ...
Try this: ``` CASE WHEN MyField IS NULL THEN 0 ELSE 1 END ``` Here it is in your code: ``` SELECT DISTINCT t.Name, CONVERT(VARCHAR(10), t.DischargeDateTime, 120) AS DischargeDate, t.PatientPortalEnabled, t.Allergy, CONVERT(VARCHAR(10), t.AllergyUpdateTime, 120) AS AllergyUpdate, CASE WHEN t.MyField IS NULL THEN 0 EL...
You can do this using a [CASE](http://technet.microsoft.com/en-us/library/ms181765.aspx) statement. ``` SELECT DISTINCT t.Name, CONVERT(VARCHAR(10), t.DischargeDateTime, 120) AS DischargeDate, t.PatientPortalEnabled, t.Allergy, CONVERT(VARCHAR(10), t.AllergyUpdateTime, 120) AS AllergyUpdate, /*This is where I would li...
If not <> NULL then "xxxField" equals '1'
[ "", "sql", "sql-server-2008", "" ]
I have a table with duplicate registers of students, but each row represent a course and a status from that student. I'm using SQL SERVER 2008 Something like that: ``` +--------+-------------+-------------------------+---------------+-----------------+ | ID | STUDENT | DATE | COURSE ...
This query will find the most recent row for each Student/Course combination. It uses a [Common Table Expression](http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx) to find the most recent date for each `STUDENT`/`COURSE` combination, and then uses that CTE to get the matching rows. The end result...
``` select * from (select *,ROW_NUMBER()over(partition by COURSE,STATUS order by dates)rn from @student)t4 where rn=1 ```
Compare difference between 2 rows at the same table
[ "", "sql", "sql-server", "" ]
I've created a new database using Microsoft SQL Server Management Studio, and now I want to interact with it through LabVIEW. I already have several VIs to interact with a previous database, using the database connectivity tool kit. This database was created by someone who has since left the project and I can't find it...
The first Connectivity Toolkit VI called should be Open Connection. The existing code (VI) will either use a file or a string as an input. If the input is a string, then you will need to create a new connection string compatible with your server. You can find common SQL Server strings at <https://www.connectionstring...
Basically the workflow you have to go through is the following: * Open connection * Execute your query * Fetch data (if needed) * Close connection If you search for "Database" in the **NI Example Finder** shipped with Labview you will find a few good starting points. In particular give a look to Database Connection....
How do I connect to a database in LabView
[ "", "sql", "database", "ssms", "labview", "" ]
i want to get users with total transactions more than 50000 ``` SELECT sum(tractions.amount) as total , user_id FROM `tractions` where `total` > 50000 group by user_id ``` i get this error ``` #1054 - Unknown column 'total' in 'where clause' ``` of curse there is no total column in table but how should i write...
You need a `having` clause with aggregation totals: ``` SELECT sum(tractions.amount) as total , user_id FROM `tractions` group by user_id HAVING total > 50000; ``` EDIT: If I were writing this query, it would look like this: ``` select t.user_id, sum(t.amount) as total from tractions t group by t.user_id having...
try this ``` SELECT sum(tractions.amount) as total , user_id FROM `tractions` where sum(tractions.amount) > 50000 group by user_id ```
select sum(amount) as total with condition on total
[ "", "mysql", "sql", "" ]
I have a table instructor and I want to delete the records that have salary in a range An intuitive way is like this: ``` delete from instructor where salary between 13000 and 15000; ``` However, under safe mode, I cannot delete a record without providing a primary key(ID). So I write the following sql: ``` delete ...
Googling around, the popular answer seems to be ["just turn off safe mode"](https://stackoverflow.com/questions/11448068/mysql-error-code-1175-during-update-in-mysql-workbench): ``` SET SQL_SAFE_UPDATES = 0; DELETE FROM instructor WHERE salary BETWEEN 13000 AND 15000; SET SQL_SAFE_UPDATES = 1; ``` If I'm honest, I ca...
You can trick MySQL into thinking you are actually specifying a primary key column. This allows you to "override" safe mode. Assuming you have a table with an auto-incrementing numeric primary key, you could do the following: ``` DELETE FROM tbl WHERE id <> 0 ```
mysql delete under safe mode
[ "", "mysql", "sql", "" ]
I have four tables and I need to find the average of each score for a particular id. I do not need the ENTIRE Column average, but the average of each record with the same id in each table. I have tried this: ``` SELECT DISTINCT M.system_id, S.name, SUM(A.Score + WAL.score + F.score + WIN.score) / 4 AS avgScore FROM...
No `Sum` needed (and no grouping too) ``` SELECT DISTINCT M.system_id, S.name, (IsNull(A.Score, 0) + IsNull(WAL.score, 0) + IsNull(F.score, 0) + IsNull(WIN.score, 0)) /4 as avgscore FROM dbo.T3_MovementSystemJoin AS M INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id INNER JOIN T3_ApplicationSystemJo...
If you don't want NULL values to become zeros and included in the average: ``` SELECT DISTINCT M.system_id, S.name, X.avgScore FROM dbo.T3_MovementSystemJoin AS M INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id INNER JOIN T3_ApplicationSystemJoin AS A ON A.Application_id = @application_id INNER JOIN T3_...
MSSQL How do I get average of four records from different tables?
[ "", "sql", "sql-server", "" ]
How to Generate Fibonacci series in sql ! I need to generate Fibonacci series 0 1 1 2 3 5 8 13 21 ... N I did this easily using C-code I need to do this using Sql !
Try this ! ``` declare @a int declare @b int declare @c int Declare @i int set @a=0 set @b=1 set @i=0 set @c=0 Print 'Fibonacci Series' print @a print @b while @i<10 Begin set @c=@a+@b print @c set @i=@i+1 set @a=@b set @b=@c end ``` # Outputs ! ``` Fibonacci Series ``` 0 1 1 2 3 5 8 13 21 34 55 89
**Try This Simple Query:** 1) For Result In Row-by-Row (Single Column, Multiple Rows) ``` WITH Fibonacci (PrevN, N) AS ( SELECT 0, 1 UNION ALL SELECT N, PrevN + N FROM Fibonacci WHERE N < 1000000000 ) SELECT PrevN as Fibo FROM Fibonacci OPTION (MAXRECURSION 0); ``` *Output 1:* ![e...
How to generate Fibonacci Series
[ "", "sql", "sql-server", "" ]
This is my table ``` create table table1(action1 varchar(10),view1 varchar(10)) insert into table1 values('A1','VIEW'),('A1','EDIT'),('A2','VIEW'),('A3','VIEW'),('A3','EDIT') ``` I need output like this ! ``` action1 VIEW EDIT A1 VIEW EDIT A2 VIEW NULL A3 VIEW EDIT ``` I tried using pivot but I get ...
``` select * from table1 pivot ( max(view1) for view1 in([VIEW],[EDIT]) )as piv; ``` # `See Demo`
By using MAX() function you can get the result > ``` > SELECT action1, > MAX( CASE view1 WHEN 'View' THEN view1 ELSE '' END ) ViewCol, > MAX( CASE view1 WHEN 'Edit' THEN view1 ELSE null END ) EditCol > FROM table1 > GROUP BY action1 > ```
Sql query to convert column to rows
[ "", "sql", "sql-server", "" ]
I have simple database and I thing my answer should be so simple but I can't find my answer the db is look like: ``` ----------------- name | ip ----------------- nick |192.168.1.10 john |192.168.1.1 john |192.168.1.2 john |192.168.1.3 lucy |192.168.10.1 lucy |192.168.10.2 ``` I need a query that return all the rows ...
try this query: ``` SELECT t1.* FROM table1 t1 INNER JOIN (SELECT Count(name) counter, name FROM table1 GROUP BY name)t2 ON t1.name = t2.name ORDER BY counter; ``` *[SQL Fiddle](http://sqlfiddle.com/#!15/199f3/5)*
Here a [SQL Fiddle](http://sqlfiddle.com/#!2/42219/10) Try this statement. ``` SELECT * FROM tblSAMPLE ORDER BY name DESC,ip ```
How to order the query result by count() of field in postgresql without group by
[ "", "sql", "postgresql", "" ]
I'm inserting data problematically into tables. When I do this from another table, it's swift, only slowed very slightly if there are a lot of records. Even then, it's a matter of seconds. When I insert from a query to a table, it goes into minutes - roughly a minute for every 1,000 records inserted. The source query...
You are using a user defined function (UDF) ConcatRelated, so the UDF runs for each record, otherwise, usually Access SQL works in the normal way.
I have written a pretty basic module that should accomplish this for you very quickly compared to your current process. Note you will need to re-name your project to something other than "Database" on the project navigation pane for this to work I have assumed that table1 and table2 are the same as you have above tabl...
When inserting data from a query to a table, does the query run for each record inserted?
[ "", "sql", "ms-access", "vba", "ms-access-2010", "" ]
I have the following table ``` Index BookNumber 2 51 2 52 2 53 1 41 1 42 1 43 ``` I am trying to come up with the following output ``` Index BookNumber1 Booknumber2 Booknumber3 ---------------------------------------------- 1 41 ...
I am not quite sure how the `index` in your query matches the `index` column in your data. But the query that you want is: ``` SELECT index, max(CASE WHEN index = 1 THEN Booknumber END) AS BookNumber1 , max(CASE WHEN index = 2 THEN Booknumber END) AS BookNumber2, max(CASE WHEN index = 3 THEN Bookn...
Assuming there are always 3 or fewer book numbers for each index, you could use: ``` with data as (select idx, booknumber as bn1, lag(booknumber, 1) over(partition by idx order by idx, booknumber) as bn2, lag(booknumber, 2) over(partition by idx order by idx, booknumber) as bn3 from boo...
Combing multiple rows into one row
[ "", "sql", "sql-server", "t-sql", "" ]
i have field name birthdate in users database some users birthdate like = > 2014/02/18 and some others like = > 2014-02-18 i should use birthdate varchar (10) so i want change 2014/02/18 to 2014-02-18 ``` SELECT `birthdate` FROM `users` WHERE `birthdate` LIKE '%%%%/%%/%%' REPLACE '%%%%-%%-%%' ``` this code ju...
You want an update statement if you want to change the data: ``` update users set birthdate = replace(birthdate, '/', '-') where birthdate like '%/%/%'; ``` You should, however, learn to store dates as dates and not as strings.
If you just want to replace `/` with `-` you can do comparison like this: ``` SELECT `birthdate` FROM `users` WHERE replace( `birthdate`, '/', '-' ) LIKE '2014-02-18' ``` Otherwise, remove both `/` and `-` from date field values and compare for `YYYYMMDD` formatted value. ``` SELECT `birthdate` FROM `users` WHE...
update field of table
[ "", "mysql", "sql", "replace", "phpmyadmin", "" ]
I'm trying to create a invoice type report where i have a header, main body with a table (which includes a totals section) and footer. The problem im getting is, the table height in the main body depends on how many rows are returned from my SPROC, hence if there is not much data, the table will take up a small portio...
In the end I've settled for a solution which is very close to what I need and involves in using hidden elements. (similar to what Dan Andrews suggested - but catered to what I needed) So first of all, I have included the totals in the footer of the report so that it stays at the bottom all the time. This is shown bel...
All of this can be achieved in the report design itself. Here's what you know: * The height of the page (P) * The height of your static data (S) * The height of your header (H) * The height of your data row (R) * The count of data rows (C) * The height of your footer (F) So you can work out how big the remaining spac...
SSRS Reports - force table to expand to bottom of page
[ "", "sql", "reporting-services", "" ]
I have the following query: ``` select'Amount' as Amount, ('£'+ CAST(SUM(rc.[Fee Charge] +rc.[Fee Charge VAT] +rc.ExtraCharges+rc.ExtraChargesVAT+rc.OtherCharges+rc.OtherChargesVAT+rc.WaitingCharge+rc.[WaitingCharge VAT])AS nvarchar(50))) AS [CompletedTurnover], ('£'+ CAST(SUM(rin.[Fee Charge] +rin.[Fee Charge VAT] +r...
You can use a union to get the results you need: ``` select 'Completed turnover' Description, ( '£'+ CAST(SUM(rc.[Fee Charge] + rc.[Fee Charge VAT] + rc.ExtraCharges+ rc.ExtraChargesVAT+ rc.OtherCharges+ ...
This process to convert columns into rows is actually called an UNPIVOT. You can do this a few different ways. **UNPIVOT:** function: ``` ;with cte as ( select'Amount' as Amount, ('£'+ CAST(SUM(rc.[Fee Charge] +rc.[Fee Charge VAT] +rc.ExtraCharges+rc.ExtraChargesVAT+rc.OtherCharges+rc.OtherChargesVAT+rc.Waiting...
Unpivot from existing query
[ "", "sql", "sql-server", "sql-server-2012", "unpivot", "" ]
**BACKGROUND** I have two tables: `drugDistributionHistory` - details what/when drugs were distributed ti patients. `drugPrices` - prices of drugs. For this example, I am looking at drug called "FLUOXETINE", also known as "PROZAC". If I query for this drug in the `drugPrices` table, I yield these results: ``` SEL...
Since you did put the percent signs on both sides of the `LIKE` operator, I suspect that you incorrectly believe that `LIKE` is symmetric; it is not. You do not get a match because neither `'%Fluoxetine%'` nor `'%Prozac%'` matches `'%Fluoxetine / Prozac%'` from the `drugDistributionHistory` table on the right side of t...
I think ``` INNER JOIN drugPrices dp ON ('%' + dp.drugName + '%' like '%' + ddh.drugName + '%' OR '%' + dp.drugBrandName + '%' like '%' + ddh.drugName + '%') ``` Should be ``` INNER JOIN drugPrices dp ON (dp.drugName like '%' + ddh.drugName + '%' OR dp.drugBrandName like '%' + ddh.drugN...
Joining with wildcard not matching strings
[ "", "sql", "sql-server", "join", "wildcard", "" ]
I'm new to SQL, and thinking about my datasets relationally instead of hierarchically is a big shift for me. I'm hoping to get some insight on the performance (both in terms of storage space and processing speed) versus design complexity of using numeric row IDs as a primary key instead of string values which are more ...
I wouldn't be concerned about space considerations primarily. An integer key would typically occupy four bytes. The varchar will occupy between 1 and 21 bytes, depending on the length of the string. So, if most are just a few characters, a `varchar(20)` key will occupy more space than an integer key. But not an extraor...
Gordon is right (which is no surprise). Here are the considerations for you not to worry about, in my view. When you're dealing with dozens of megarows or less, storage space is basically free. Don't worry about the difference between INT and VARCHAR(20), and don't worry about the disk space cost of adding an extra c...
What are the merits of using numeric row IDs in MySQL?
[ "", "mysql", "sql", "performance", "" ]
We have couple of data schemas and we investigate the migration to Liquibase. (One of data schemas is already migrated to Liquibase). Important question for us is if Liquibase supports dry run: * We need to run database changes on all schemas without commit to ensure we do not have problems. * In case of success all ...
You can try "updateSQL" mode, it will connect db (check you access rights), acquire db lock, generate / print SQL sentences to be applied (based on db state and you current liquibase change sets) also it will print chageset id's missing in current state of db and release db lock.
Unfortunately, no. By default, Liquibase commits the transaction executing all statements of a changeset. I assume that the migration paths you have in mind usually involve more than a single changeset. The only way you can modify the transaction behavior is the `runInTransaction` attribute for the `<changeset>` tag,...
Does Liquibase support dry run?
[ "", "sql", "transactions", "liquibase", "" ]
Simplified example: Two tables - people and times. Goal is to keep track of all the times a person walks through a doorway. A person could have between 0 and 50 entries in the times table daily. What is the proper and most efficient way to keep track of these records? Is it ``` times table ----------- person_id time...
The second solution has some problems: * Since you need to access individual timestamps1, `serialized_timestamps_for_the_day` cannot be considered [atomic](http://en.wikipedia.org/wiki/First_normal_form#Atomicity) and would violate the 1NF, causing a [bunch of problems](https://stackoverflow.com/a/3653574/533120). * O...
Consider what are we talking about here. Accounting for just raw data `(event_time, user_id)` this would be `(4 + 4) * 1M ~ 8MB` per 1M rows. Let's try to roughly estimate this in a DB. One integer 4 bytes, timestamp 4 bytes; row header, say 18 bytes -- this brings the first estimate of the row size to `4 + 4 + 18 = 2...
Proper way to create dynamic 1:M SQL table
[ "", "sql", "performance", "database-design", "architecture", "one-to-many", "" ]
Hey I have the column named UID , which current data is like below ``` uid --- 0 0 0 0 0 0 0 0 0 ``` I want to fill the value from 1 to N. So for example below ``` uid --- 1 2 3 4 5 6 7 8 9 . . n ``` How can i loop through all row and increment values.
You can only define a column as AUTO\_INCREMENT if it is a PRIMARY KEY and an INT ! Since you want the UID to be set as AUTO\_INCREMENT, why not make it as PRIMARY KEY ``` CREATE TABLE TableName ( UID INT AUTO_INCREMENT PRIMARY KEY, -- other columns... ) ```
``` $n = 50; //number of your records suppose it was 50 for($i=1; $i<=$n; $i++) { $res = mysql_query("select * from `table name` where `UID`=0 LIMIT 1 "); if($row = mysql_fetch_assoc($res)) { mysql_query("update `table name` set `UID`='$i' where UID=0 limit 1 ") or die(mysql_error) } }...
Sql increment particular column from 1 to N
[ "", "mysql", "sql", "" ]
I like using stored procedures in ASP.NET and want to make sure I have the exact correct syntax. Are there any significant differences between these? ``` ALTER PROCEDURE dbo.mySP @param1 AS BEGIN SET NOCOUNT ON SELECT f1 FROM foo WHERE f2 = @param1 END RETURN ``` What if we don`t use begin, end, o...
None of the things you have mentioned will affect performance, and in reality it is personal preference, but here are my thoughts: No you don't need `RETURN` unless you want to change the return value from the default of 0. This can be useful for [returning error codes](http://technet.microsoft.com/en-us/library/ms190...
I always include `SET NOCOUNT ON` on the very first line after `BEGIN` statement. If you are reading SP with application and `SET NOCOUNT OFF` is set on SP. You will get results plus message back. And if you not handling return of that additional message you could run into problems. That is why it is best to `SET NOC...
Where exactly to set NOCOUNT ON in stored procedure?
[ "", "asp.net", "sql", "t-sql", "" ]
my English is not very good, but i try to explain my self clear. i need advice. i am selecting from one table sum of values of each field. and my query looks like this : ``` SELECT * FROM ( SELECT SUM(Clicks) AS sales , 'sales' as type FROM ClicksPerDay WHERE BannerID = 3456 UNION SELECT SUM(Clicks) AS rent, ...
Try the following: ``` SELECT SUM( IF(BannerId = 3456, Clicks, 0) ) AS sales, SUM( IF(BannerId = 3457, Clicks, 0) ) AS rents FROM ClicksPerDay WHERE BannerID IN (3456, 3457) ```
Like this: ``` SELECT sales = SUM(sales), rent = SUM(clicks) FROM ( SELECT SUM(Clicks) AS sales , 0 as rent FROM ClicksPerDay WHERE BannerID = 3456 UNION ALL SELECT 0 as sales, SUM(Clicks) AS rent FROM ClicksPerDay WHERE BannerID = 3457 ) total ```
mysql UNION query output
[ "", "mysql", "sql", "" ]
I have a table as such: ``` |testNr |date | |1 | 2014-01-01 | |2 | 2014-01-03 | |3 | 2014-01-03 | ``` And another one like: ``` |finalID | testNr | from_date |to_date |1 | 1 | 2013-12-01 |2013-12-20 |2 | 1 | 2013-12-25 |2014-01-05 |3 ...
I think this is what you want ``` select t1.testNr, t1.date, t2.finalID from table1 t1 left join table2 t2 on t1.testNr=t2.testNr and t1.date between t2.from_date and t2.to_date ``` [fiddle](http://sqlfiddle.com/#!6/be125/2)
Use the following ``` SELECT t1.*, t2.finalID FROM table1 t1 LEFT JOIN table2 t2 on t1.testNR=t2.testNR and t1.[date] between t2.from_date and t2.to_date ``` [SQLFIddle](http://sqlfiddle.com/#!3/02348/3)
Joining based on condition per row
[ "", "sql", "sql-server", "join", "" ]
I have this query: ``` $sql = "SELECT catalogs_values.name as word, catalogs.name as catalog FROM catalogs_values INNER JOIN catalogs ON catalogs_values.catalog_id = catalogs.id WHERE catalogs_values.id NOT IN (SELECT valueid FROM monitor WHERE ...
Try replacing the `not in` with a `left outer join` or `not exists`: ``` SELECT cv.name as word, c.name as catalog FROM catalogs_values cv INNER JOIN catalogs c ON cv.catalog_id = c.id LEFT JOIN monitor m on cv.id = m.valueid and userid=$user_id WHERE m.valueid is null and cv.checked = 0 ORDER BY R...
Ordering by Mysql's RAND is ALWAYS slow, I use a very fast way to sort this: 1. select min and max ID from the table 2. run a php rand(min\_Id, max\_Id) 3. make a loop until you find an id that's really existing, believe me it's really fast if the id is a unique key as it should 4. once you are sure the ID exists exit...
Improve MySQL random
[ "", "mysql", "sql", "" ]