Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
To my best knowledge of MySQL this not a possible thought in this case would be helpful. We want to `select` a record in a parent table and concat (something like that) the child rows in the `select`. Here in obviously wrong MySQL but to illustrate what we want to achieve. ``` SELECT parentattr, CONCAT ( ...
You also need a `GROUP BY`, plus you need to specify exactly which name is being concatenated. ``` SELECT parentattr1, parentattr2, GROUP_CONCAT(c.name ORDER By c.name) FROM parent p LEFT JOIN child c ON parentId = c.id GROUP BY parentattr1, parentattr2 ```
Try using GROUP\_CONCAT (), here are [examples](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat). You also have an extra `)` after parent.id.
Concat child records in parent SELECT
[ "", "mysql", "sql", "" ]
I have an `Insert Into Select` statement with a `Case When` clause. I want to execute a stored procedure within the `When` statement. ``` Insert into Orders(id, custId, custIntake) Select id, custId custIntake = Case When ( Exec mySProc(custId) = 1 ) = 'InStore' When ( Exec mySProc(custId) = 0 ) = 'Outsi...
I would suggest you convert your 'mySProc' procedure into a Scalar User Defined Function if you want to run it like this. Stored Procedures are not able to do what you want.
If I understand correctly then what you need is code to run when the WHEN statement is true. Just use CASE > WHEN > THEN as described here: <http://msdn.microsoft.com/en-us/library/ms181765.aspx> Hope this helps.
Execute a stored procedure within a case statement
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "case-when", "" ]
How can I concat a character to MySQL results except for the last result? So: ``` friends ------------- friend-a friend-b friend-c friend-d friend-e ``` I now do `select concat(friends,',') from friends` which actually gives me each friend name with a `,`, but I don't need the `,` for the last one. I cannot use gro...
if you dont want to use group concat (which would be the optimal way to do this.. you can remove the last row then add back on with a union or use an aggregate function on your string to return the largest. ``` (select concat(friends,',') as friend from friends WHERE friends <> (SELECT friends f...
I guess that you want the output so that you can use it in the `IN` parameter of sql? If yes, then you can use the following :- ``` select * from `some_other_table` where `friends` in (select `friends` from `friends`); ``` Tell me if I am wrong
MySql concat a character except for the last record
[ "", "mysql", "sql", "" ]
Suppose I have a table : ``` start_range end_range 1 4 4 8 ``` I want the result to be true if it is greater than any of the value of start\_range and less than any of the corresponding end\_range. Eg. value 2 should return `true` , as `2>1` and `2<4` but val...
Assuming that `xyz` is your table: ``` select (count(*) > 0) as HasMatch from xyz where value > start_range and value < end_range; ``` I'm not sure why you are using `some`. EDIT: It occurs to me that you want to use subqueries, and `xyz` is not the table in question. Perhaps this is what you want: ``` select xyz....
``` select (count(*) > 0) as HasMatch from (select IF(start_range<value and end_range>value, true, false ) as value from XYZ having value =1) as MatchTable ``` [DEMO](http://sqlfiddle.com/#!2/bb8fc/31)
query using SOME in mysql not giving expected results.?
[ "", "mysql", "sql", "" ]
``` query = "SELECT highest_score FROM users ORDER BY CAST(highest_score AS UNSIGNED) DESC"; ``` I have a table where the `highest_score` column is **VARCHAR**(it should be **INT**) but that's not the question. The question is why does the query return this: 1. -10 2. 255 3. 241 4. 231 5. 125 > Since I a...
Casting **negative** values to `unsigned` causes integer overflow, that's why `-10` considered as the largest value.
You are casting it to `UNSIGNED` which can not store negative values. Cast it to `SIGNED`. Executing `SELECT CAST('-10' AS UNSIGNED)` reveals the reason: UNSIGNED overflows when you are trying to cast a negative value. The above statement's result is `18446744073709552000` which is high enough to be the first when you...
Cast as INT, sort by DESC issue
[ "", "mysql", "sql", "" ]
I am creating a site that is sort of ecommerce-ish. I want to give my users a perfect search ability using specific attributes that differ from product to product. I plan to create 1 products table storing the basic information that is shared among products i.e Name, Description, Price and a few others. Then I plan to ...
Don't use separate details tables for each category, use a generic details table that can store any attribute. Its columns would be: ``` Product_ID INT (FK to Products) Attribute VARCHAR Value VARCHAR ``` The unique key of this table would be `(Product_ID, Attribute)`. So if `Product_ID = 1` is a computer, you would...
Since this is an application so you must be generating the queries. So lets generate it in 2 steps. I assume you can add a column product\_type\_id in your Product table that will tell you which child table to user. Next create another table Product\_type which contains columns product\_type\_id and query. This query c...
Store a unique reference to a Mysql Table
[ "", "mysql", "sql", "database", "performance", "database-design", "" ]
I have an `update` statement that's like this: ``` update user_stats set requestsRecd = (select count(*) from requests where requestedUserId = 1) where userId = 1, requestsSent = (select count(*) from requests where requesterUserId = 2) where userId = 2; ``` What I'm trying to do, is update the same table, bu...
(*As proposed in several other answers, obviously, you could run two separate statements, but to answer the question you asked, whether it was possible, and how to do it...*) Yes, it is possible to accomplish the update operation with a single statement. You'd need conditional tests as part of the statement (like the ...
What you're trying to do is two updates try splitting these out: ``` update user_stats set requestsRecd = (select count(*) from requests where requestedUserId = 1) where userId = 1; update user_stats set requestsSent = (select count(*) from requests where requesterUserId = 2) where userId = 2; ``` There may b...
Using WHERE clauses in an UPDATE statement
[ "", "mysql", "sql", "" ]
I try to find duplicate rows between two tables. This code works only if records are not duplicated: ``` (select [Name], [Age] from PeopleA except select [Name], [Age] from PeopleB) union all (select [Name], [Age] from PeopleB except select [Name], [Age] from PeopleA) ``` How to find missing, duplicate records. `Robe...
You can use `UNION ALL` to concat both tables and `Group By` with `Having` clause to find duplicates: ``` SELECT x.Name, x.Age, Cnt = Count(*) FROM ( SELECT a.Name, a.Age FROM PersonA a UNION ALL SELECT b.Name, b.Age FROM PersonB b ) x GROUP BY x.Name, x.Age HAVING COUNT(*) > 1 ``` --- Ac...
I like Tim's answer but you need to check in both tables if the records are missing. He is only checking if the records are missing in table A. Try this to check if records are missing in either of the tables and how many times. ``` Select *, 'PersonB' MissingInTable, a.cnt - isnull(b.cnt,0) TimesMissing From ( Selec...
Finding duplicate differences between two tables in sql
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I have this SQL query for SQL Server 2008 R2: ``` Declare @fechaDesde DateTime Declare @fechaHasta DateTime set @fechaDesde = '01/01/2014 00:00:00.000' set @fechaHasta = '31/12/2014 23:59:59.999' Select Cuenta, isnull(sum(SaldoDebe), 0) as SumaDebe, isnull(sum(SaldoHaber), 0) as SumaHaber, isnull(sum(SaldoD...
Try this updated query,I removed the multiple `isnull` and added `else 0` in case to handle nulls. ``` DECLARE @fechaDesde DATETIME DECLARE @fechaHasta DATETIME SET @fechaDesde = '01/01/2014 00:00:00.000' SET @fechaHasta = '31/12/2014 23:59:59.999' Select Cuenta, sum(SaldoDebe)as SumaDebe, sum(SaldoHaber)as SumaHabe...
The driver of performance isn't the `case` statements. It is the `join`, `where`, and `group by`. ``` From Cuentas c inner join Diario d on c.Código = d.Cuenta Where d.Pista in ('00') and d.Fecha >= @fechaDesde and d.Fecha <= @fechaHasta ``` I would recommend the following indexes: `diario(P...
How to improve this SQL Server query with multiple 'CASE'?
[ "", "sql", "sql-server", "case", "" ]
My query. ``` UPDATE assets SET assets.Amount = (SELECT SUM(assets.Amount) - NEW.Amount FROM assets WHERE NEW.UserId = assets.UserId and NEW.AccountId = assets.AccountId) AS TmpAssets WHERE NEW.UserId = assets.UserId and NEW.AccountId = assets.AccountId ```
MySQL does not allow you to use the table being updated in a subquery in an `update` or `delete`. It is easy enough to get around this. Here is one approach using `update`/`join`: ``` UPDATE assets a JOIN (select sum(a.Amount) as sumamount, a.UserId, a.AccountId from assets a where NEW.UserId =...
Try this : ``` UPDATE assets SET assets.Amount = (select temp.val from (SELECT (SUM(assets.Amount) - NEW.Amount) val from assets WHERE NEW.UserId = assets.UserId and NEW.AccountId = assets.AccountId) temp) WHERE NEW.UserId = assets.UserId and NEW.AccountId = assets.AccountId ; ```
You can't specify target table 'assets' for update in FROM clause
[ "", "mysql", "sql", "" ]
I want to add an extra column, where the max values of each group (ID) will appear. Here how the table looks like: ``` select ID, VALUE from mytable ``` > ID VALUE > 1 4 > 1 1 > 1 7 > 2 2 > 2 5 > 3 7 > 3 3 Here is the result I want to get: > ID VALUE max\_values > 1 4 7 > 1 1 7 > 1 7 7 > 2 2...
Your previous questions indicate that you are using SQL Server, in which case you can use [window functions](http://msdn.microsoft.com/en-GB/library/ms189461.aspx): ``` SELECT ID, Value, MaxValue = MAX(Value) OVER(PARTITION BY ID) FROM mytable; ``` Based on your comment on another answer about fi...
There is no need to use GROUP BY in subselect. ``` select ID, VALUE, (select MAX(VALUE) from mytable where ID = t.ID) as MaxValue from mytable t ```
Add a column with the max value of the group
[ "", "sql", "" ]
I would like to execute a SELECT, where it selects a column-value only if that column exists in the table, else display null. This is what I'm currently doing: ``` SELECT TOP 10 CASE WHEN EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA ='test' and TABLE_NAME='tableName' and COLUMN_NAME='c...
You can write as: ``` SELECT CASE WHEN EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA ='test' and TABLE_NAME='tableName' and COLUMN_NAME='columnName' ) THEN ( SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA ='test' and TABLE_NAME='tableName' and C...
``` SELECT * FROM sys.columns WHERE [name] = N'columnName' AND [object_id] = OBJECT_ID(N'tableName') ``` Add this inside your case statement. Please note that this code would work only for higher version of sqlserver.[like sqlserver 2008]
SQL Server How to SELECT a column only if it exists in the table
[ "", "sql", "sql-server", "select", "case", "union", "" ]
I wanna create the following table: ``` create table product (id bigint not null, product_type varchar(50), product_name varchar(100), available_from TIMESTAMP, available_to TIMESTAMP, primary key (id)); ``` My table's key is the 'id'. when inserting in the table, I wanna that the product\_type be unique. How to do...
``` ALTER TABLE <your table name> ADD CONSTRAINT unique_product_type UNIQUE(product_type); ``` I can't see a table name in your create table SQL.
The function NEWID() generates a new unique id. Maybe you can make a trigger which insets this in every insert or make the default value to be NEWID(). Well the second option seems a bit better :P ``` CREATE TABLE Test123 ( ID NVARCHAR(200) DEFAULT (NEWID()), name NVARCHAR(100) ) INSERT INTO Test123 (name) VA...
product set a column unique without being the primary key
[ "", "sql", "db2", "" ]
I have an Exam Table and a query to get a list of exams: ``` CREATE TABLE [dbo].[Exam] ( [ExamId] INT IDENTITY (1, 1) NOT NULL, [Title] NVARCHAR (50) NULL, CONSTRAINT [PK_Exam] PRIMARY KEY CLUSTERED ([ExamId] ASC) ); SELECT Exam.ExamId AS ExamId, Exam.Title ...
There are a couple of ways to do this, I prefer to use `EXISTS`: ``` SELECT E.ExamId AS ExamId, E.Title AS Name FROM Exam E WHERE EXISTS ( SELECT 1 FROM AdminTest A WHERE A.ExamId = E.ExamId AND A.TestStatusID = 3) ``` --- Alternatively, you could use `IN`: ``` SELECT Exa...
You can use `EXISTS` as the other answer shows, you can also add `TestStatusID = 3` to your `JOIN`: ``` SELECT e.ExamId AS ExamId, e.Title AS Name FROM Exam e JOIN AdminTest a ON e.ExamID = a.ExamID AND a.TestStatusId = 3 ``` Or filter in a `WHERE` clause: ``` SELECT e....
How can I join a table to another to do a select conditional upon a value in a column in the second table?
[ "", "sql", "sql-server", "" ]
In order to implement password complexity I need a function that can remove repeating characters (in order to generate passwords that will meet the password complexity requirements). So a string like weeeeee1 will not be allowed since the e is repeated. I need a function that will instead return we1, where the repeatin...
I think you can achieve your goal using regexp\_replace. Or do I missed something? ``` select regexp_replace(:password, '(.)\1+','\1') from dual; ``` --- Here is an example: ``` with t as (select 'weeee1' password from dual union select 'wwwwweeeee11111' from dual union select 'we1' from du...
Try this: ``` select regexp_replace('weeeeee1', '(.)\1+', '\1') val from dual VAL --- we1 ```
Oracle remove repeating characters
[ "", "sql", "oracle", "plsql", "" ]
I have a table with a column for customer names, a column for purchase amount, and a column for the date of the purchase. Is there an easy way I can find how much first time customers spent on each day? So I have ``` Name | Purchase Amount | Date Joe 10 9/1/2014 Tom 27 ...
The following is standard SQL and works on nearly all DBMS ``` select date, sum(purchaseamount) as total_first_time_purchase from ( select date, purchaseamount, row_number() over (partition by name order by date) as rn from the_table ) t where rn = 1 group by date; ``` The deriv...
The two key concepts here are `aggregates` and `sub-queries`, and the details of which dbms you're using may change the exact implementation, but the basic concept is the same. 1. For each name, determine they're first date 2. Using the results of 1, find each person's first day purchase amount 3. Using the results of...
Finding the first occurrence of an element in a SQL database
[ "", "sql", "" ]
I got some serial keys to find in sql database, such as “A-B-C”,”D-E-F”,”G-H-I”,”J-K-L” and they are stored in tblTemp using ntext data type. These above keys may store in three columns, colA, colB and colC (sometimes store in one column and the rest are null). Sometimes, two serial keys can find in one column (e.g. A-...
You have to convert/cast your search term as an appropriate data type, in this case `text`. Try this: ``` Declare @sa TABLE(var1 nvarchar(Max)); Insert INTO @sa(var1) VALUES (N’A-B-C’); Insert INTO @sa(var1) VALUES (N’D-E-F’); Insert INTO @sa(var1) VALUES (N’G-H-I’); Insert INTO @sa(var1) VALUES (N’J-K-I’); SELECT *...
[CAST/CONVERT](http://msdn.microsoft.com/en-us/library/ms187928%28v=sql.90%29.aspx) (msdn.microsoft.com) your var1 to NTEXT type in your query so that the types are compatible. ``` SELECT * FROM tblTemp WHERE colA IN ( SELECT CAST(var1 AS NTEXT) FROM @sa ); ```
SQL Query Finding From Table DataType Declaration
[ "", "sql", "sql-server", "t-sql", "" ]
I have two tables, Staff and Cust\_Order. I want to add the column 'First name' from the staff table while still performing the below code: ``` Select Staff_No Count(*) AS "Number Of Orders" From Cust_Order Group by Staff_No; ``` Thanks
Join the orders and staff tables, then group by will need to include the additional column(s) ``` SELECT co.Staff_No , s.First_name , COUNT(*) AS "Number Of Orders" FROM Cust_Order co INNER JOIN Staff s on co.Staff_No = s.Staff_No GROUP BY co.Staff_No , s.First_name ; ```
``` SELECT DISTINCT STAFF_NO, FIRST_NAME, COUNT (*) OVER (PARTITION BY STAFF_NO) AS "Number Of Orders" FROM CUST_ORDER; ``` Used distinct as there might be duplicate results in case first\_name is not unique.
Select count from one table, and columns from another ORACLE
[ "", "sql", "oracle", "count", "" ]
I have a stored procedure in SQL Server 2008 that is used to fetch data from a table. **My input parameters are:** ``` @category nvarchar(50) = '', @departmentID int ``` **My Where clause is:** ``` WHERE A.departmentID = @departmentID AND A.category = @category ``` Is there any way I can apply a Case...
you can modify your `WHERE` clause as follow: ``` WHERE A.departmentID = @departmentID AND (@category = '' or A.category = @category) ```
``` WHERE A.departmentID = @departmentID AND ((@category = '') or (@category <> '' AND A.category = @category)) ``` This should give you what you want as a result set, it basically doing a check for either a blank category which should then return all results for the department id or just the category specified in t...
SQL Server: How to handle two different cases in Where clause
[ "", "sql", "sql-server", "case", "where-clause", "" ]
Please reference code below... ``` Private Sub Save_Click() On Error GoTo err_I9_menu Dim dba As Database Dim dba2 As Database Dim rst As Recordset Dim rst1 As Recordset Dim rst2 As Recordset Dim rst3 As Recordset Dim SQL As String Dim dateandtime As String Dim FileSuffix As String Dim folder As ...
I solved this by recreating the table in SQL instead of up-sizing it out of Access.
Just a guess here, but I'm thinking you've got a typo that's resulting in assigning a Null to a required field. Change "Locaton": ``` rst.Fields("Site") = DLookup("Folder", "Locaton", "Loc_ID='" & Forms!frmUtility!Site & "'") ``` To "Location": ``` rst.Fields("Site") = DLookup("Folder", "Location", "Loc_ID='" & For...
3146 ODBC Call Failed - Access 2010
[ "", "sql", "ms-access", "odbc", "subroutine", "" ]
I am having trouble determining the best way to compare dates in SQL based on month and year only. We do calculations based on dates and since billing occurs on a monthly basis the date of the month has caused more hindrance. For example ``` DECLARE @date1 DATETIME = CAST('6/15/2014' AS DATETIME), @date2 DAT...
To handle inequalities, such as between, I like to convert date/times to a YYYYMM representation, either as a string or an integer. For this example: ``` DECLARE @date1 DATETIME = CAST('6/14/2014' AS DATETIME), @date2 DATETIME = CAST('6/15/2014' AS DATETIME), @date3 DATETIME = CAST('7/1/2014' AS DATETI...
You can filter the month and year of a given date to the current date like so: ``` SELECT * FROM tableName WHERE month(date2) = month(getdate()) and year(date2) = year(getdate()) ``` Just replace the `GETDATE()` method with your desired date.
SQL Server date comparisons based on month and year only
[ "", "sql", "sql-server", "sql-server-2008", "date", "" ]
Having a table that storage customer names, I need to duplicate those records and add a character at the end at the same time. For example I have: ``` CNAME customer1 customer2 customer3 ``` I would like to return: ``` CNAME customer1 customer1* customer1# customer2 customer2* customer2# customer3 customer3* custom...
You can union your results together: ``` select cname from table1 union all select cname + '*' from table1 union all select cname + '#' from table1 order by cname ``` You can see it working in [this fiddle](http://sqlfiddle.com/#!3/f540e/4)
I would use a number-table and this query: ``` with c as ( select c.*, rn=row_number()over(order by cname) from customers c ) select cname = cname + case n % 3 when 1 then '' when 2 then '*' when 0 then '#' END from numbers n join c on n between 1 and 3 order by ...
How to duplicate and add more characters to a string row in sql?
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table in SQL Server: ``` T_Id Supplimentary_keywords ------------------------------------------------------------------------------------------- 1 Animal, Animals, 1, One, Single,live,living Organism 2 Animals, Animal, Two, 2,live,living Organism 3 Animals, Animal, Three, 3,live,living Or...
Try this.. ``` SELECT distinct Split.a.value('.', 'VARCHAR(100)') data FROM (select id,Cast ('<M>' + replace(Replace(suppl, ',', '</M><M>'),'&','&amp;') + '</M>' AS XML) AS Data from #temp) AS A CROSS APPLY Data.nodes ('/M')...
``` create table #temp (id int,suppl varchar(1000)) insert into #temp select 1 , 'Animal, Animals, 1, One, Single,live,living Organism' union all select 2 , 'Animals, Animal, Two, 2,live,living Organism' union all select 3 , 'Animals, Animal, Three, 3,live,living Organism' union all select 4 , 'Anim...
how to select rows data as single column in sql server
[ "", "sql", "sql-server", "t-sql", "" ]
I've got 512 rows to insert to a database. I'm wondering if there is any advantage to submitting multiple inserts over one large insert. For example 1x 512 row insert -- ``` INSERT INTO mydb.mytable (id, phonenumber) VALUES (1, 555-555-5555) , (2, 555-555-5555) , (3, 555-555-5555), //repeat to id = 512 ``` VS 4x 128...
My answer is assuming SQL Server; I suspect what I say would be applicable to other SQL engines. Much of the overhead of any SQL Server query is development of an execution plan. If you do this as a single insert, it will have to develop the execution plan one (1) time; if you do 512 seperate inserts, it will have to ...
The answer is likely to vary based on which RDBMS product you're using. One can't make a fine-grained optimization plan in an implementation-agnostic way. But you can make broad observations, for example it's better to [remove loop-invariant code](https://en.wikipedia.org/wiki/Loop-invariant_code_motion). In the case...
Which would be fastest, 1x insert 512 rows, 4x insert 128 rows, or 512x insert 1 rows
[ "", "sql", "database", "performance", "language-agnostic", "query-performance", "" ]
I have this t-sql script below that I need to modify to insure that there are no duplicate rows from table1. I would like to do that by grabbing the rows that have the most current date in the [ImportedDate] column. Could I get some guidance? Thanks UPDATE FOR CLARIFICATION I need to select all rows in table1 that mat...
Updated with the Answer for anyone looking. FYI: I know there is extraneous code in the inner select but this statement is dynamically generated from a c# application where the user is able to select the columns they want to view. So the column selection code is only be generated once and added to a string.Format stat...
Add ``` ORDER BY [ImportedDate] DESC ``` to the bottom of the query.
Selecting Rows from Table with Lastest Import Date
[ "", "sql", "t-sql", "" ]
While trying to build a data warehousing application using Talend, we are faced with the following scenario. We have two tables tables that look like Table master ``` ID | CUST_NAME | CUST_EMAIL ------------------------------------ 1 | FOO | FOO_BAR@EXAMPLE.COM ``` Events Table ``` ID | CUST_ID | EVENT_NAME...
To do this in Talend you'll need to first sort your data so that it is reliably in the order of applied, opened and closed for each account and then denormalize it to a single row with a single delimited field for the dates using the tDenormalizeRows component. After this you'll want to use tExtractDelimitedFields to ...
Yeah, this is a good idea, this is called a cumulative snapshot fact. <http://www.kimballgroup.com/2012/05/design-tip-145-time-stamping-accumulating-snapshot-fact-tables/> Not sure how to do this in Talend (dont know the tool) but it would be quite easy to implement in SQL using a Case or Pivot statement
How to flatten a one-to-many relationship
[ "", "sql", "data-warehouse", "talend", "dimensional-modeling", "" ]
Table name: `mytable` ``` Id username pizza-id pizza-size Quantity order-time -------------------------------------------------------------- 1 xyz 2 9 2 09:00 10/08/2014 2 abc 1 11 3 17:45 13/07/2014 ``` This is `mytable` which has 6 columns. `Id...
If the requirement is like count the number of orders with different pizza quantities and represent count of orders as : 1, 2, 3, 4, 5, 6,7 and consider all above order counts in new category : 'above 7' then you can use window function as: ``` select case when totalorders < = 7 then cast(totalorders as varchar(10)) ...
Try ``` Select CASE WHEN Quantity > 7 THEN 'OVER7' ELSE Cast(quantity as varchar) END Quantity, COUNT(ID) NoofOrders from mytable GROUP BY CASE WHEN Quantity > 7 THEN 'OVER7' ELSE Cast(quantity as varchar) END ``` or ``` Select SUM(Case when Quantity = 1 then 1 else 0 end) Orders1, SUM(Case when Quantity = 2 th...
Count in sql with group by
[ "", "sql", "sql-server", "t-sql", "" ]
Let's say I have two tables: ``` Table foo =========== id | val -------- 01 | 'a' 02 | 'b' 03 | 'c' 04 | 'a' 05 | 'b' Table bar ============ id | class ------------- 01 | 'classH' 02 | 'classI' 03 | 'classJ' 04 | 'classK' 05 | 'classI' ``` I want to return all the values of foo and bar for which foo exists in more t...
``` select f.val, b.class from foo f join bar b on f.id = b.id where f.val in ( select f.val from foo f join bar b on f.id = b.id group by f.val having count(distinct b.class) > 1 ); ```
you can just use a subquery that has all duplicated to display each row using EXISTS like so. ``` SELECT f.val, b.class FROM foo f JOIN bar b ON b.id = f.id WHERE EXISTS ( SELECT 1 FROM foo JOIN bar ON foo.id = bar.id WHERE foo.val = f.val GROUP BY foo.val HAVING COUNT(DISTINCT bar.class) > 1 )...
Select the foo in distinct bar from 2 tables
[ "", "mysql", "sql", "" ]
I have wrote SQL to select user data for last three months, but I think at the moment it updates daily. I want to change it so that as it is now October it will not count Octobers data but instead July's to September data and change to August to October when we move in to November This is the SQL I got at the moment:...
``` WHERE LastLoggedIn >= DATEADD(month, DATEDIFF(month, 0, GETDATE())-3, 0) AND LastLoggedIn < DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0) ``` The above statement will return any results in July till before the start of current month.
Referencing this answer to get the first day of the month: **[How can I select the first day of a month in SQL?](https://stackoverflow.com/a/1520803/57475)** You can detect the month limitations like so: ``` select DATEADD(month, DATEDIFF(month, 0, getdate()) - 3, 0) AS StartOfMonth select DATEADD(month, DATEDIFF(mo...
SQL Last Three Months
[ "", "sql", "sql-server", "reporting", "" ]
i have a table follower and following count.. want to get the count of both in one stored procedure.. is it possible to have two select queries with different where condition on same table possible? ``` CREATE TABLE Table1 ([val1] int, [val2] int, [val3] int, [val4] int, other int) ; INSERT INTO Table1 ([val...
You could do this: ``` SELECT SUM(CASE WHEN val2=26 THEN 1 ELSE 0 END) AS following_count, SUM(CASE WHEN val3=26 THEN 1 ELSE 0 END) AS follower_count FROM table1 ```
Why don't you fire both statement using UNION ALL ? See: <http://dev.mysql.com/doc/refman/5.1/de/union.html> SO: ``` SELECT COUNT(*) AS following_count FROM table1 WHERE val2=26 UNION ALL SELECT COUNT(*) AS following_count FROM table1 WHERE val3=26 ``` returns two rows with 2 numbers in 1 query. In two columns do ...
two select queries with different where clause on same table
[ "", "mysql", "sql", "sql-server", "stored-procedures", "" ]
I have the following table: ``` ID GROUPID oDate oTime Value 1 A 2014-06-01 00:00:00 100 2 A 2014-06-01 01:00:00 200 3 A 2014-06-01 02:00:00 300 4 A 2014-06-01 03:00:00 400 5 A 2014-06-01 04:00:00 0 6 A ...
You can write as: ``` ;with CTE as ( select T1.ID, T1.GROUPID, T1.oDate, T1.oTime, T1.Value, --T2.oTime as previousrow, --T3.oTime as nextrow, case when T1.Value = 0 then 0 --E3=0 else T1.Value - T2.Value --(E3-E2) end as Result From tes...
I think i got it for you ! test this ``` SELECT DISTINCT A.*, CASE WHEN A.VALUE = 0 THEN ( B.RESULT + C.RESULT ) / 2 ELSE A.RESULT END AS RESULT FROM (SELECT A.*, A.VALUE - B.VALUE AS RESULT FROM #TEMP1 A JOI...
previous and next record on calculation field SQL
[ "", "sql", "sql-server", "excel", "sql-server-2008", "t-sql", "" ]
Following is my table for artists - ``` id name sex 1 harsh male 2 geet female ``` Following is my table for events - ``` id artist_id created_by 2 2 16 2 2 17 ``` Following is my query - ``` SELECT * FROM `events` WHERE artist_id IN (SELECT id FROM `artists` WHERE name LIKE '%...
Try this query ``` SELECT e.* FROM `artists` AS a JOIN `events` AS e ON e.artist_id = a.id WHERE a.name LIKE '%$search_term%'; ```
You need to select from two tables simultaneously. Use the [join](http://dev.mysql.com/doc/refman/5.0/en/join.html) for that ``` SELECT artists.name, events.* FROM artists INNER JOIN events ON artist.id = artist_id WHERE name LIKE '%search_term%' ```
Add columns when using IN in mysql for the result
[ "", "mysql", "sql", "" ]
I have a table that has an [ArchiveDate] column like this: ``` ArchiveDate 2014-10-06 2014-10-06 2014-10-06 2014-10-01 2014-10-01 2014-10-01 2014-10-01 2014-05-22 2014-05-22 ``` I want to select the penultimate date, but when I use: ``` select max([ArchiveDate]) -1 'previousweek' from [PipelineArchive] ``` I get 20...
You need to sort on `ArchiveDate` in descending order, skip one record, and take the next one. For example, in SQL Server 2012 you could do it this way: ``` SELECT DISTINCT [ArchiveDate] FROM [PipelineArchive] ORDER BY [ArchiveDate] DESC OFFSET (1) ROWS FETCH NEXT (1) ROWS ONLY ``` [Demo.](http://www.sqlfiddle.com/#!...
``` SELECT distinct([ArchiveDate]) FROM [PipelineArchive] WHERE [ArchiveDate] = (SELECT MAX([ArchiveDate]) AS second FROM [PipelineArchive] WHERE [ArchiveDate] < (SELECT MAX([ArchiveDate]) AS first FROM [PipelineArch...
SQL - select the penultimate date
[ "", "sql", "" ]
I need to determine whether a customer has bought 100 or more unique drinks using a SQL query and so far I've done: ``` SELECT COUNT(DISTINCT beer_id) FROM Orders WHERE patron_email='smith@gmail.com' ``` How would I test whether the result of this is 100 or more? Update: Sorry for the vague question, ...
This works in MySQL, not sure about others: ``` SELECT COUNT(DISTINCT beer_id) > 100 FROM Orders WHERE patron_email='smith@gmail.com' ``` Just put a boolean condition in the `SELECT`. It will evaluate to 0 for false or 1 for true.
By using the `having` clause as in: ``` SELECT COUNT(DISTINCT beer_id) FROM Orders WHERE patron_email='smith@gmail.com' having count(distinct beer_id) > 100 ```
Getting true/false from SQL query
[ "", "sql", "" ]
I have three tables : ``` FORM(id) QUESTION(id, form_id, text) --> X questions for a form ANSWER(id, question_id, answer_number, text) --> X answers for a question ``` I also have a table for answers given by users : ``` USERS_ANSWERS(id, question_id, answer_number) ``` I would like to have, for each question, t...
A simple JOIN should do it; ``` SELECT q.id question_id, a.answer_number, COUNT(ua.id) answer_count FROM question q JOIN answer a ON q.id = a.question_id LEFT JOIN users_answers ua ON q.id = ua.question_id AND a.answer_number = ua.answer_number GROUP BY q.id, a.answer_number ORDER BY q.id, a.answer_number ``` T...
You simple need to group by (question\_id, answer\_number) and then count it ``` select question_id, answer_number, count(answer_number) as count from user_answers group by question_id, answer_number order by question_id, answer_number ```
SQL multiple join with count
[ "", "sql", "join", "count", "" ]
I'm trying to learn SQL and I downloaded a database to practice. I downloaded two files of extension .sql, one is the schema and the other one the actual data. I've also installed MySQL Workbench. I've been googling and I've been trying things to solve this but I don't understand Workbench and I can't load the database...
This is simple in Workbench, and I'll use the freely available sakila database as an example. Feel free to apply this to your situation: 1. Download "sakila" from here: <http://dev.mysql.com/doc/index-other.html> 2. Extract it somewhere, in my case, onto the Desktop into a new sakila-db/ directory 3. Open Workbench 4....
The accepted answer is from 4 years ago, so I thought I'd give an update as in MySQL Workbench 6.3 the procedure is a bit different. You have to select the menu item *Server -> Data Import -> Import from Self-Contained File* and select the SQL file containing the database you want to import. In *Default Target Schema...
Importing Data and Schema to MySQL Workbench
[ "", "mysql", "sql", "mysql-workbench", "" ]
I have a column of type DATE stored data are contains date and time . I can see value when i do ``` select CAST(MSG_DT AS TIMESTAMP) from table; ``` this is the output ``` 17-MAR-08 15:38:59,000000000 ``` I have to select the row using * Only date ``` select CAST(MSG_DT AS TIMESTAMP) from MWRB_...
Try this: ``` SELECT * FROM your_table WHERE TO_CHAR (start_date, 'yyyy-mm-dd') = '2014-10-06' AND TO_CHAR (start_date, 'hh24:mi:ss') > '10:00:00' ```
Why are you casting the column value to a TIMESTAMP when the column in the database is a DATE type? The fractional part of the seconds will always be 0, as DATE only has resolution to the seconds value. You need to add the hours,minutes, and seconds format specifier to the query: ``` select MSG_DT from MWRB_RECEIVE w...
Oracle query time on date fields
[ "", "sql", "oracle", "select", "time", "" ]
So I have this code that I am trying to figure out and I am not sure how exactly to copy my input from one table to another. Say I have this input ``` Insert into TABLE Value ('blah'); ``` and I want to get that value I just inserted and insert it into another table ``` Insert into ANOTHERTABLE value ('blah'); ``` ...
``` delimiter // create table first_table (fieldname varchar(20)); create table second_table (fieldname varchar(20)); create trigger insert_into_second before insert on first_table for each row begin insert into second_table (fieldname) values (new.fieldname); end // insert into first_table...
Your looking to insert from a select statement. ``` INSERT INTO TABLE (column_name) SELECT column_name FROM ANOTHERTABLE ``` As far as "get that value I just inserted" - you'd just run your insert twice of course - secondly on the new table. You could select the data you just inserted from the database and pop int...
How can I copy a mysql input to another table?
[ "", "mysql", "sql", "" ]
I need to build a query with a order by and rownum but without use a sublect. It is needed to get the first row of the query ordered. In other words, I want the result of ``` select * from ( SELECT CAMP1,ORDERCAMP FROM TABLENAME ORDER BY ORDERCAMP) where rownum=1; ``` but **whithout use a subselect**. Is it possible...
Your current query (without the invalid `ORDER BY`) gets `ORA-01427: single-row subquery returns more than one row`. You can nest subqueries, but you can only refer back one level when joining; so if you did: ``` SELECT T1.CAMP_ID, T2.CAMP, (SELECT CAMP FROM FROM (SELECT OT.CAMP FROM OTHERTABLE OT WHER...
In the most recent version of Oracle, you can do: ``` SELECT CAMP1, ORDERCAMP FROM TABLENAME ORDER BY ORDERCAMP FETCH FIRST 1 ROWS ONLY; ``` Otherwise, I think you need a subquery of some sort.
How to use order by and rownum without subselect?
[ "", "sql", "oracle", "sql-order-by", "rownum", "" ]
I have seen similar questions but feel this is not a duplicate question. I would like to concatenate rows into single string with joins. I am confused on how to proceed. Syntax below I am getting an error "There is already an object named '#TEMPTABLE' in the database." also I am not sure if my sytax to the 2nd select s...
What worked in my situation was IF OBJECT\_ID('tempdb.#TEMPTABLE') IS NOT NULL DROP TABLE #Results GO Thank you all!
The error message `There is already an object named '#TEMPTABLE' in the database.` means that you've created a temporary table with this name in a previous run. To solve this, you need to `DROP` this table or use another name. To drop, use the following code before your query: ``` IF OBJECT_ID('tempdb..#TEMPTABLE') I...
Concatenate rows into a single text string
[ "", "sql", "sql-server", "" ]
I'm sure this in easy one, but I can't go past conceptualization to syntax: I have a table of features where one named feature may populate several rows e.g: ``` [NAME], [GUID] Fred, NULL Fred, NULL Fred, NULL Tom, Null Mary, Null Mary, Null Mary, Null Mary, Null ``` What I'd like to do is assign ONE GUID per name: ...
``` DECLARE @tmp TABLE ( Name varchar(30), GUID uniqueidentifier ) INSERT @tmp SELECT x.Name, NEWID() FROM (SELECT DISTINCT Name FROM MyTable) x UPDATE MyTable SET GUID = tmp.GUID FROM MyTable t INNER JOIN @tmp tmp ON t.Name = tmp.Name ```
Because `NEWID()` doesn't materialize until the very end of a query, you will need to materialize it temporarily. Here I use a table variable to store a single new GUID per name (by grouping on `Name`) before using that table to update the final destination: ``` DECLARE @MaterializedGuids TABLE ( Name varchar(20),...
Loop and assign non-unique GUID to sets of values?
[ "", "sql", "sql-server", "sql-server-2008", "guid", "" ]
I know this may be quite simple, but its very late and for the life of me I cannot remember how to do it. I have four tables, A,B and C. Each one has an ID, Name and some other columns. What I need is a table E that has ID, Name\_A, Name\_B and Name\_C . So if I add another name to say B, it will update this new E ta...
You could use a union. Like this: ``` SELECT dbo.TableA.name FROM dbo.TableA UNION SELECT dbo.TableB.name FROM dbo.TableB UNION SELECT dbo.TableC.name FROM dbo.TableC ``` This will get you to output: ``` Juan Mario Pedro ```
TRY LIKE THIS : ``` Create View VwNames as SELECT distinct dbo.TableA.name AS NameA, dbo.TableB.name AS NameB, dbo.TableC.name AS NameC FROM dbo.TableA TA LEFT JOIN ON TA.col1=TB.col1 dbo.TableB TB LEFT JOIN ON TB.col1=T.col1 ...
Creating a table or view from one field in other tables
[ "", "sql", "sql-server", "t-sql", "" ]
I'm rather inexperienced with databases and have just read about the ["n+1 selects issue"](https://stackoverflow.com/questions/97197/what-is-the-n1-selects-issue). My follow-up question: **Assuming the database resides on the same machine as my program, is cached in RAM and properly indexed, why is the n+1 query patter...
You are correct that avoiding n+1 selects is less important in the scenario you describe. If the database is on a remote machine, communication latencies of > 1ms are common, i.e. the cpu would spend millions of clock cycles waiting for the network. If we are on the same machine, the communication delay is several ord...
> Assuming the database resides on the same machine as my program **Never** assume this. Thinking about special cases like this is never a good idea. It's quite likely that your data will grow, and you will need to put your database on another server. Or you will want redundancy, which involves (you guessed it) anothe...
Why is the n+1 selects pattern slow?
[ "", "sql", "orm", "select-n-plus-1", "" ]
I have this table in Oracle database 11g: ``` NUNOTA SEQUENCIA QTD_CONTROLE QTDNEG ---------- ---------- ------------ ---------- 446 1 30 60 446 2 30 30 446 3 30 120 ``` I need to obtain a result like that: ...
Try this: ``` with t_res (NUNOTA,SEQUENCIA,QTD_CONTROLE,QTDNEG, lvl) as ( select NUNOTA,SEQUENCIA,QTD_CONTROLE,QTDNEG, 1 from t union all select t.NUNOTA,t.SEQUENCIA,t.QTD_CONTROLE,t.QTDNEG, t_res.lvl + 1 from t, t_res where t_res.lvl < t.QTDNEG/t.QTD_CONTROLE ) select unique NUNOTA,SEQUENCIA,QTD_CONT...
A recursive solution (available from Oracle 11gR2): ``` with t(nunota, sequencia, qtd_controle, qtdneg) as (select nunota , sequencia , qtd_controle , qtdneg from mytable union all select nunota , sequencia , qtd_controle , qtdneg - qtd_controle from t w...
Select Oracle result two lines for same cases
[ "", "sql", "oracle", "select", "view", "oracle11g", "" ]
I have a pretty basic execution of a stored procedure in my code: ``` Dim objCmd As ADODB.Command Dim objConn As ADODB.Connection Dim rsTemplate As ADODB.Recordset Set objConn = New ADODB.Connection objConn.Open strConnection Set objCmd = New ADODB.Command objCmd.ActiveConnection = objConn objCmd.CommandType = adCmdS...
If your `strConnection` is such that you are specifiying a forward-only cursor, then the record count will always be `-1` as the result-size cannot be identified with that kind of connection. From here <http://msdn.microsoft.com/de-de/library/windows/desktop/ms676701(v=vs.85).aspx> > The cursor type of the Recordset ...
Make sure in your stored procedure `GetTemplate`, you have enabled the row count. Example: ``` CREATE procedure [dbo].[GetTemplate] AS BEGIN SET NOCOUNT OFF -- Enable row count here ... END ```
ADODB RecordSet RecordCount doesn't return useful information
[ "", "sql", "vb6", "adodb", "" ]
I have this simple SQL ``` SELECT (CASE WHEN (SELECT Name FROM Customers WHERE Customers_id = Customer) IS NOT NULL THEN (SELECT Name FROM Customers WHERE ...
You could use `IFNULL` like this: ``` IFNULL((SELECT Name FROM Customers WHERE Customers_id = Customer),Customer) ``` Or `COALESCE` like this: ``` COALESCE((SELECT Name FROM Customers WHE...
Try this ``` SELECT IsNull(Name,Customer) AS Customer, DateStart, ProgramsRun.Programs_id, RunInSeconds, SwSQL, SwProgram, Name AS ProgramName FROM ProgramsRun LEFT JOIN Programs ON ProgramsRun.Programs_id = Programs.Programs_id; ```
How to avoid conditional multiple SELECT in a query
[ "", "mysql", "sql", "" ]
``` mysqldump -t -u root -p mytestdb mytable --where=datetime LIKE '2014-09%' ``` This is what I am doing and it returns: ``` mysqldump: Couldn't find table: "LIKE" ``` I am trying to return all the rows where the column `datetime` is `like 2014-09` meaning "all September rows".
You may need to use quotes: ``` mysqldump -t -u root -p mytestdb mytable --where="datetime LIKE '2014-09%'" ```
Selecting dates using LIKE is not a good idea. I saw this method in one project. This causes huge DBMS load and slow system operation as no index by this table column used. If you need to select date range use between: ``` where datetime between '2014-09-01' and '2014-09-30 23:59:59' ```
mysqldump with --where clause is not working
[ "", "sql", "mysql", "" ]
I have a query that unions together some selects from two different tables I currently end up with the final result as so: ``` ColA ColB ColC ------------------------- 1 | NULL DEF 1 2 | ABC DEF 1 3 | NULL GBY 1 ``` Column B will have a maximum of two records with the sam...
Maybe you could use a CTE with `ROW_NUMBER`: ``` WITH CTE AS ( SELECT ColA, ColB, ColC, RN = row_number() over (partition by ColB Order By ColA DESC) FROM dbo.TableName -- or your query ) SELECT ColA, ColB, ColC FROM CTE WHERE RN = 1 ``` [Sql-Fiddle](http://sqlfiddle.com/#!6/e596f/1/0)
``` IF OBJECT_ID('tempdb..#test') IS NOT NULL DROP TABLE #test CREATE TABLE #test (Col1 char(10), col2 char(10)) INSERT INTO #test(Col1,col2) VALUES (NULL,'DEF'), ('ABC','ABC'), (NULL,'DEF') select distinct * from #test where col2 is not null or col1 in ( select col1 from #test group by col1 having max(co...
Distinct Union with null
[ "", "sql", "sql-server", "" ]
I have a `users` table and a `likes` table. A user gets displayed a random other user's data and can decide whether he likes or dislikes it. I am struggling with selecting a new random user partner for the acting user that he has not yet rated! Now, I am trying to select all users that do not have a row in the `likes`...
You can use `not exists` to select all users that have not partnered with a certain user yet ``` select * from db_users dbu where not exists ( select 1 from db_likes dbl where dbl.relation in ('dislike','like','maybe') -- not sure if this is necessary and dbl.user = $oUser->id and dbl.partner = dbu.id ...
I think the sql you want is: ``` select db_users.*, db_likes.* from db_users left join db_likes on db_users.id = db_likes.partner and db_likes.user = 'Sx12cltADam2XvzBMUMwq7DG' and db_likes.relation <> 'dislike' and db_likes.relation <> 'like' and db_likes.relation <> 'maybe' whe...
Sql select row if no row exists in other table
[ "", "sql", "" ]
I have the following table: ``` oDate value1 value2 value3 value4 2014-06-01 10 20 30 40 2014-06-02 20 25 35 50 ``` I want to have the following result ``` oDate oField oValue 2014-06-01 Value1 10 2014-06-01 Value2 20 2014-06-01 ...
You could do this: **Test data:** ``` DECLARE @tbl TABLE(oDate DATETIME,value1 INT,value2 INT,value3 INT,value4 INT) INSERT INTO @tbl VALUES ('2014-06-01',10,20,30,40), ('2014-06-02',20,25,35,50) ``` **UNPIVOT query** ``` SELECT * FROM ( SELECT oDate, value1, value2, value3, ...
Try this ``` SELECT DISTINCT ODATE,VALUE,FIELD FROM (SELECT odate,value1,value2,value3,value4 FROM #temp) p UNPIVOT (VALUE FOR FIELD IN (value1,value2,value3,value4) )AS unpvt; GO ```
Horizontal to Vertical View SQL
[ "", "sql", "sql-server", "sql-server-2008", "" ]
How can I use information from the dictionary views to get information on all types of data declared in a given package in Oracle 11g.
Use PL/Scope ... ``` alter session set plscope_settings = 'IDENTIFIERS:ALL'; ``` ... and recompile the package (`UTL_LOG` in my case) ... ``` alter package utl_log compile; alter package utl_log compile body; ``` ... and then query the `user_identifiers` view ... ``` select name, type, object_name, object_type, li...
If you want to know how a package looks like run: `desc PACKAGE_NAME`: ``` SQL> desc dbms_output PROCEDURE DISABLE PROCEDURE ENABLE Argument Name Type In/Out Default? ------------------------------ ----------------------- ------ -------- BUFFER_SIZE NUMBER(38) ...
How to get information on all types of data declared in a given package
[ "", "sql", "database", "oracle", "" ]
I'm using `PostgreSQL 9.2`. Is there any way to get an output like, > Database : mydb, User : myUser using a **`SELECT`** query?
By using the inbuilt [System Information Functions](https://www.postgresql.org/docs/curren/functions-info.html#FUNCTIONS-INFO) 1.) Currently using database ``` select current_database() ``` 2.) Connected User ``` select user ``` To get the desired output use either this ``` select 'Database : ' ||current_da...
Check [this part of the manual](http://www.postgresql.org/docs/current/interactive/functions-info.html) for more functions. ``` SELECT current_user, user, session_user, current_database(), current_catalog, version(); ```
How to get current database and user name with `SELECT` in PostgreSQL?
[ "", "sql", "database", "postgresql", "select", "" ]
Here's my query ``` SELECT tum.user_id, tum.first_name, tum.last_name FROM di_webinar t LEFT JOIN tbl_event_registrants ter ON ter.event_ref_id = t.webinar_ref_id LEFT JOIN tbl_event_attendees tea ON tea.event_ref_id = t.webinar_ref_id INNER JOIN tbl_user_master tum ON tum.user_id = ter.user_ref_id OR tum.user_id...
In your comments you said, you don't have to show a sample Webinar per user. Then you don't even have to select from the Webinar table. After all you simply want all users that had a part in a Webinar. So select from tbl\_user\_master and make sure the user id is mentioned in one of the two tables tbl\_event\_registran...
try this one : ``` SELECT tum.user_id, tum.first_name, tum.last_name FROM di_webinar t LEFT JOIN tbl_event_registrants ter ON ter.event_ref_id = t.webinar_ref_id LEFT JOIN tbl_event_attendees tea ON tea.event_ref_id = t.webinar_ref_id INNER JOIN tbl_user_master tum ON tum.user_id = tea.user_ref_id WHERE t.d...
Mysql Inner Join with OR condition - Query optimization
[ "", "mysql", "sql", "left-join", "inner-join", "" ]
I have two columns in my database I'd like to combine to make a new third column. The first column is a company name and the second is the URL to the company website. I'd like to make a new column that is the company name hyperlinked to the website: ``` <a href="http://companywebsite.com>Company Name</a> ``` Is ther...
As Polvonjon write, use CONCAT: ``` SELECT brief_description, CONCAT('<a href="', link, '">', innovation_name, '</a>') FROM inno_db ``` By the way - `inno_db` is a very odd name for a table in the database; it's a particular type of storage engine for MySQL. Do you not think "companies" is a better name? Creating a ...
Try use CONCAT function: ``` SELECT company, url, CONCAT('<a href="', url, '">', company, '</a>') FROM companies ``` But I will not advice to using this sample of getting anchor tag. Try to use VIEW element in your MVC app.
Create new column in mySQL using values from other columns
[ "", "mysql", "sql", "" ]
I have 3 tables. On the first table, there are multiple entries for each project. The second is basically a mapping table. It's more complicated than this, but for this example I've simplified. There's a simple condition I'm checking for on table 2. On the third table, each entry has a flag that's set to true or false....
The following should do what you want: ``` select t1.* from table1 t1 where not exists (select 1 from table2 t2 join table3 t3 on t2.id = t3.id where t2.name = t1.name and t3.active <> false ); ``` There is some ambigui...
A fairly straight forward JOIN with HAVING should give you the results you want; ``` SELECT t1.project, t1.client FROM table1 t1 JOIN table2 t2 ON t1.client = t2.name JOIN table3 t3 ON t2.id = t3.id GROUP BY t1.project, t1.client HAVING NOT MAX(t3.active) ``` [An SQLfiddle to test with](http://sqlfiddle.com/#!2/94d88...
sql query join where none of the many meet a condition
[ "", "sql", "join", "" ]
My table looks like this: ``` Cell Date Hour Minute Counter Value AB1 20141008 14 15 C1 40 AB1 20141008 14 15 C2 15 AB1 20141008 14 30 C1 30 AB1 20141008 14 30 C2 13 ``` I need to calculate formula PERCENT, whic...
*if the data were horizontal and C1, C2 were column* You could PIVOT the data to make it so: ``` SELECT Cell, Date, Hour, SUM([C2])*100/SUM([C1]) AS [%], SUM([C2])/CAST(SUM([C1]) AS DECIMAL(10,5)) AS [Percent] FROM TABLE1 PIVOT (SUM(value) FOR Counter in ([C1],[C2]) ) AS pvt GROUP BY Cell, Date, Hour ``` [Sa...
You do that like this: ``` SELECT Cell, Date, Hour, SUM(CASE WHEN Counter = 'C2' THEN Value ELSE 0 END) / SUM(CASE WHEN Counter = 'C1' THEN Value ELSE 0 END) AS Percent FROM [table] group by Cell, Date, Hour ```
Group vertical data for sums that will be used in division?
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
Not giving detailed information about the table structure and the data: What might be the reason, that this group by: ``` select c.state, case when age <20 then 'u20' when (age >=20 and age<30 ) then 'o20' when (age >=30 and age<40 ) then 'o30' when (age >=40 and age<50 ) then 'o40' else 'min50' end age_group, count...
If you want to group by AGE\_GROUP you need to, er, group by AGE\_GROUP. ``` select state, age_group, count(*) amount_trans, sum(t.SELLING_PRICE) sum_price from ( select c.state, case when age <20 then 'u20' when (age >=20 and age<30 ) then 'o20'...
Its because you are grouping by age, state. Did you mean group by age\_group, state?
SQL - Group by not grouping as expected
[ "", "sql", "oracle", "group-by", "" ]
I am brand new to mysql so please excuse my level of knowledge here, and feel free to direct me in a better direction if what I am doing is out of date. I am pulling information from a database to fill in a php page. My tables: Server: ``` |ServerID (int) | ArticleID (int) | locationID (int) | | 1 | ...
Check this ``` SELECT SUBSTRING_INDEX(location, '-', 1) as LID,Article.Name,Count(*) as Count from Location join Server on Server.locationID=Location.locationID join Article on Article.ArticleID=Server.ArticleID group by LID,Article.ArticleID ; ``` [DEMO](http://sqlfiddle.com/#!2/9cd922/14)
Please give this a shot: ``` SELECT s.locationID as id, a.name, count(*) as count FROM `Server` s LEFT JOIN `Article` a ON s.ArticleID = a.ArticleID GROUP BY s.locationID, a.name ```
Big Mysql Query (Join counts in the result and modify a string)
[ "", "mysql", "sql", "count", "" ]
I'm in the process of converting Python code over to the new SQLAlchemy-based Pandas 0.14.1. A common pattern we use is (generically): ``` connection = db.connect() # open connection/session sql = 'CREATE TEMP TABLE table1 AS SELECT ...' connection.execute(sql) ... other sql that creates TEMP tables from various j...
You can now pass SQLAlchemy connectable to `pandas.read_sql`. From the [docs](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html): > pandas.read\_sql(sql, con, index\_col=None, coerce\_float=True, params=None, parse\_dates=None, columns=None, chunksize=None) > > ... > > con : SQLAlchemy connec...
All you need to do is add 'SET NOCOUNT ON' at the beginning of your query, that way pandas read\_sql will read everything as one statement. ``` sSQL = '''SET NOCOUNT ON CREATE TABLE ...... ''' ```
How can pandas.read_sql_query() query a TEMP table?
[ "", "sql", "python-2.7", "pandas", "sqlalchemy", "netezza", "" ]
I have for example following data: ``` shift date value ---------------------- A 2014-07-01 5 A 2014-07-02 8 A 2014-07-03 2 B 2014-07-03 1 C 2014-07-03 9 ``` How to create view, where will be all the shifts (A,B,C) in each day? ``` shift date value -----------------...
Here is example if you don't want to put missing dates... ``` DECLARE @table TABLE (shift CHAR(1), date Date, Value INT) INSERT INTO @table SELECT 'A', '2014-07-01', 5 INSERT INTO @table SELECT 'A', '2014-07-02', 8 INSERT INTO @table SELECT 'A', '2014-07-03', 2 INSERT INTO @table SELECT 'B', '2014-07-03', 1 INSERT IN...
First cross-join the shifts with the dates to get all combinations. Then left join all combinations you already have in your table. ``` select shift.shift, dates.date, coalesce(mytable.value,0) from (select distinct shift from mytable) shifts cross join (select distinct date from mytable) dates left join mytable on my...
Repeatedly fill missing 0 values
[ "", "sql", "sql-server", "" ]
How do I do this in SQL: 1. `SELECT CLIENT, PAYMENT_CODE FROM PAYMENTS_TABLE` 2. `If PAYMENT_CODE = 1, SELECT other data from table_1` 3. `Else, SELECT other data from table_2` The results I want are: ``` | Client | Payment Code = 1 | Address from table_1 | Phone from table_1 | ... ``` or ``` | Client | Payment Co...
You didn't tell us how table\_1 and table\_2 are linked to payments\_table, but something like this should work: ``` select p.client, p.payment_code, case when payment_code = 1 then t1.address else t2.address end as address, case when payment_code = 1 then t...
Although Rajesh's solution is fine, you can also do it using two LEFT JOINs; ``` SELECT pt.CLIENT, pt.PAYMENT_CODE, COALESCE(t1.address, t2.address) address, COALESCE(t1.phone, t2.Phone) phone FROM PAYMENTS_TABLE pt LEFT JOIN Table_1 t1 ON pt.client_code = t1.client_code AND pt.PAYMENT_CODE = 1...
SQL - SELECT from a table if a certain condition is met, else SELECT from another
[ "", "sql", "db2", "" ]
i have the following table RENTAL(book\_date, copy\_id, member\_id, title\_id, act\_ret\_date, exp\_ret\_date). Where book\_date shows the day the book was booked. I need to write a query that for every day of the month(so from 1-30 or from 1-29 or from 1-31 depending on month) it shows me the number of books booked. ...
The following query would give you all days in the current month, in your case you can replace `SYSDATE` with your date column and join with this query to know how many for a given month ``` SELECT DT FROM( SELECT TRUNC (last_day(SYSDATE) - ROWNUM) dt FROM DUAL CONNECT BY ROWNUM < 32 ) where DT >= trunc(sysdate,...
The answer is to create a table like this: table yearsmonthsdays (year varchar(4), month varchar(2), day varchar(2)); use any language you wish, e.g. iterate in java with Calendar.getInstance().getActualMaximum(Calendar.DAY\_OF\_MONTH) to get the last day of the month for as many years and months as you like, and fil...
SQL query for all the days of a month
[ "", "sql", "oracle", "" ]
Say if I have a database structure a bit like this: ``` CREATE TABLE person ( idPerson INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) ); CREATE TABLE detailTypes ( type INT NOT NULL AUTO_INCREMENT PRIMARY KEY, field VARCHAR(50) ); CREATE TABLE details ( i...
There is no "type" field in any of your tables. Did you meant to use `idDetailType` ? Try the following: ``` SELECT * FROM detailTypes t JOIN person p LEFT JOIN details d ON p.idPerson = d.idPerson AND t.idDetailType = d.idDetailType ``` Then refine the results to avoid using that nasty `*` PD: field and value ar...
I don't have the status to comment yet so I write here. Have you tried setting your 'p' and 't' values as primary keys for the tables?
Selecting from mulitple tables, then joining to both, in MySQL
[ "", "mysql", "sql", "phpmyadmin", "" ]
Here is my table called sample. ``` id name grade sign 1 pinky A null 2 smita B sam ``` I want to add new record into sample table after checking name,grade and sign.If record not found for these combination,insert else not. ``` declare @count int select @count = count(*) from sample where ...
use if exists: ``` if not exists( select * from sample where name = @name and grade= @grade and (sign = @sign or (sign is null and @sign is null)) ) begin insert into sample(name,grade,sign) values (@name,@grade,@sign) end; ``` have a look at the example `SQL Fiddle` 6 queries of insertion, with 2 of y...
You could use a few extra checks on `null`: ``` sign = @sign or (sign is null and @sign is null) ```
How to add null value in where clause (comparison)
[ "", "sql", "asp.net", "" ]
This must be very trivial but I can't seem to find the solution. I work with two tables, both without any primary key. I want to add all the records of the first table to the second table only if they don't exist. Basically: ``` INSERT INTO Table2 SELECT Table1.* FROM Table WHERE "the record to be added doesn't alr...
You could do something like this. You would need to check each relevant column - I have just put in 2 as an example. With a `Not Exists` clause you can check if a record already existed across multiple columns. With a `NOT IN` you would only be able to check if a record already existed against one column. ``` INSERT I...
you could make usage of the `EXISTS` function: ``` INSERT INTO Table2 SELECT Table1.* FROM Table1 WHERE NOT EXISTS(SELECT * FROM table2 WHERE <your expression to compare the two tables goes here>) ``` But i would advise you to check the use of unique index for your tables
SQL: insert only new records
[ "", "mysql", "sql", "ms-access-2007", "" ]
I can specify schema with CREATE TABLE or DROP TABLE: ``` sqlQuery(odbcConnect("Hive"), "DROP TABLE schema.table;") ``` but not with ALTER TABLE: ``` sqlQuery(odbcConnect("Hive"), "ALTER TABLE schema.table RENAME TO schema.new_table;") ``` Error message: ...mismatched input 'RENAME' expecting KW\_EXCHANGE near 'tab...
If possible, you might try upgrading to at least Hive 0.14.0. The issue with Hive not handling a schema in ALTER TABLE schema.table statements was resolved in Hive 0.14.0 See the following JIRA on this issue: <https://issues.apache.org/jira/browse/HIVE-9180> If you can upgrade, the original "ALTER TABLE schema.table...
I had the same problem while trying to add new partition. But then I issued 2 statements : "**use schema\_name;**" and "**alter table table\_name(without schema\_name) add partition...**" and everything went OK. Seems that ALTER statement doesn't support schema name in Hive. Try to exexute those 2 last statements separ...
RODBC: can't specify schema with ALTER TABLE command
[ "", "sql", "r", "database-schema", "rodbc", "" ]
I have a PERSON table: ![PERSON](https://i.stack.imgur.com/3afqM.jpg) To get the list of persons who have a difference between their ages less than 5 years, I try: ``` SELECT * FROM PERSON p1 CROSS JOIN PERSON p2 WHERE p1.psn_id <> p2.psn_id AND p1.psn_age - p2.psn_age <= 5; ``` So I got: ![RESULT](https://i.st...
``` SELECT * FROM PERSON p1 CROSS JOIN PERSON p2 WHERE p1.psn_id < p2.psn_id AND ABS(p1.psn_age - p2.psn_age) <= 5; ```
Try this: ``` select * from PERSON a inner join PERSON b on a.psn_id < b.psn_id and abs(a.psn_age - b.psn_age) <= 5; ``` It will put the older person on the left. If for whatever reason you'd prefer it the other way around, change `a.psn_age - b.psn_age` to `b.psn_age - a.psn_age`. Update, I have ver...
How to get rid of duplicated lines in SQL Cross Join Query result?
[ "", "sql", "" ]
I need to display date as **"Oct 10, 2014 1:06 PM"** My SQL query is ``` SELECT STUFF(CONVERT(char(19), CURRENT_TIMESTAMP, 100), 18,0, ' ') ``` and it is displaying like **"Oct 10 2014 1:06 PM"**
You already have the syntax for stuff. Why don't you just add another stuff ? ``` SELECT STUFF(STUFF(CONVERT(char(19), CURRENT_TIMESTAMP, 100), 18,0, ' '), 7,0, ',') ```
``` select CONVERT(char(13),GETDATE(),107)+CONVERT(varchar(15),CAST(GETDATE() AS TIME),100) Output Oct 10, 2014 1:24PM ```
Sql Server date format should be like " Oct 17, 2014 10:14 PM"
[ "", "sql", "sql-server", "database", "sql-server-2008", "" ]
I'm wondering why cost of this query ``` select * from address a left join name n on n.adress_id=a.id where a.street='01'; ``` is higher than ``` select * from address a left join name n on n.adress_id=a.id where a.street=N'01'; ``` where address table looks like this ``` ID NUMBER STREET VAR...
`SYS_OP_C2C` is an `internal function` which does an `implicit conversion` of `varchar2` to `national character set` using `TO_NCHAR` function. Thus, the filter completely changes as compared to the filter using normal comparison. I am not sure about the reason why the number of rows are *less*, but I can guarantee it...
When worrying about explain plans, it matters whether there are current statistics on the tables. If the statistics do not represent the actual data reasonably well, then the optimizer will make mistakes and estimate cardinalities incorrectly. You can check how long ago statistics were gathered by querying the data di...
Oracle SQL execution plan changes due to SYS_OP_C2C internal conversion
[ "", "sql", "oracle", "oracle11g", "" ]
Hi I Have Table that called Tags, in tag table I have 2 columns (QuestionID int ,Tag nvachar(100)) I want to Select Questions with all Tags in one column like the below ``` QuestionID Tag ---------- ---- 1 Math 1 Integral 2 Physics QuestionID QuestionText ---------- ----------- 1 What is 2*2? 2 ...
There are two ways to answer this: 1. can use a query like in other answer, but this is work for one table only. 2. create `clr aggregate function` for this like a below code (my code in C#). this solution work for all tables and simple for use, only use: `select Concat(column) from Table` in sql server ```...
Try this ``` create function fn_comma (@question_id int) returns varchar(100) as begin declare @value varchar(100) set @value=(SELECT top 1 STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()] FROM Tags WHERE ID = t.ID FOR XML PATH(''), TYPE) .value('.','NVARCHAR(MAX)'),1,2,' ')...
Sql Server - Is there any way to `Concat` nvarchar column in Select Such as `Agregate functions`
[ "", "sql", "sql-server", "" ]
I have a use case where I need to use ROW\_NUMBER() over PARTITION: Something like: ``` SELECT Column1 , Column 2 ROW_NUMBER() OVER ( PARTITION BY ACCOUNT_NUM ORDER BY FREQ, MAN, MODEL) as LEVEL FROM TEST_TABLE ``` I need a workaround for this in Impala. Unfortunately Impala does not support sub queries...
Impala is rather limited for this type of query. With some assumptions, this query is possible: * The four columns in the partitioning clause are never `NULL` * The four columns in the partitioning clause uniquely identify a row The query is rather ugly and expensive: ``` select tt.column1, tt.column2, count(*) as l...
ROW\_NUMBER() OVER PARTITION was added in CDH 5.2: <https://www.cloudera.com/documentation/enterprise/latest/topics/impala_analytic_functions.html#row_number> ``` ROW_NUMBER() OVER([partition_by_clause] order_by_clause) ```
ROW_NUMBER( ) OVER in impala
[ "", "sql", "window-functions", "impala", "" ]
How do you delete data from influxdb? The documentation shows it should be as simple as: ``` delete from foo where time < now() -1h ``` For some reason, influxdb rejects my delete statements saying "Delete queries can't have where clause that doesn't reference time" ``` select * from bootstrap where duration > 1000...
It appears that you can do this in influxdb 0.9. For instance, here's a query that just succeeded for me: ``` DROP SERIES FROM temperature WHERE machine='zagbar' ``` (Per generous comment by @MuratCorlu, I'm reposting my earlier comment as an answer...)
With influx, you can only delete by time For example, the following are invalid: ``` #Wrong DELETE FROM foo WHERE time < '2014-06-30' and duration > 1000 #Can't delete if where clause has non time entity ``` This is how I was able to delete the data ``` DELETE FROM foo WHERE time > '2014-06-30' and time < '2014-06-...
Can you delete data from influxdb?
[ "", "sql", "influxdb", "" ]
I have 2 fields I want to send values to within a `WHERE` statement. * If a variable = 0 then set 2 field values to 100. * If the variable = 1 then set those same 2 field values to 101. In my imaginary world, somehow this would work: ``` Where CASE WHEN @ReportType = 0 THEN od.StatusCd = 100 AND odm.StatusCd = ...
If I have understood what you are trying to do, this should work : ``` Where ( (@ReportType = 0 AND od.StatusCd = 100 AND odm.StatusCd = 100) OR (@ReportType = 1 AND od.statusCd = 101 AND odm.StatusCd = 101) ) And od.CompletionDate between .... And so on.... ```
Alternatively you could rewrite your CASE conditions in the form of a join, like below: ``` ... INNER JOIN ( VALUES (0, 100, 100), (1, 101, 101) ) AS v (ReportType, odStatusCd, odmStatusCd) ON @ReportType = v.ReportType AND od.statusCd = v.odStatusCd AND odm.StatusCd = v.odmStatusCd WHERE od.Completion...
Where clause depending of the value of a variable
[ "", "sql", "sql-server", "t-sql", "case", "where-clause", "" ]
I want to compare the data between two tables (data1 & data2) as the request: ``` SELECT COUNT(email) FROM data2 WHERE data2.email NOT IN (SELECT email FROM data1) ``` But each table are so big, data1 => 25 millions, data2 => 38 millions of tuples. So this request is awesome for small tables but sooo long for biger l...
Be aware that you count emails repeatedly. If an email is in 100 records in data2 and not in data1, then you count 100, not 1. To get the query fast, you need an index on both data1.email and data2.email. Then the dbms doesn't actually even have to access the tables; it can work on the indexes only. To count each ema...
``` SELECT COUNT(email) FROM data2 WHERE not exists (select 1 from data where data2.email = data.email) ```
Compare data from two tables
[ "", "sql", "linux", "postgresql", "debian", "" ]
I am trying to get query like this ``` SELECT sales.action_date, sales.item_id, items.item_name, sales.item_quantity, sales.item_price, sales.net FROM sales INNER JOIN items ON sales.item_id = items.ID GROUP BY sales.item_id HAVING (((sales.action_date)=[Forms]![rep_frm]![Text13].[value])); ``` Every time ...
You don't have any aggregations like SUM in your SELECT statement. I also don't understand why you sales.action\_date is in de HAVING clause. This is for aggregated filtering like SUM(sales.item\_price) <> 0. It should be possible to put this part in de WHERE-clause, before the GROUP BY instead of the HAVING clause. Th...
When you are grouping your data all fields in select query should be either included in `group by` clause, or some aggregate function should be applied to it - otherwise it doesn't makee sense. By the way - as far as I can see, you should use `WHERE(((sales.action_date)=[Forms]![rep_frm]![Text13].[value]))` before gro...
MS access query aggregation
[ "", "sql", "vba", "ms-access", "ms-access-2013", "" ]
I have a following table (simplified version) in SQLServer. ``` Table Events ----------------------------------------------------------- | Room | User | Entered | Exited | ----------------------------------------------------------- | A | Jim | 2014-10-10T09:00:00 | 2014-10-10T09:10:00 | |...
The basic query is: ``` select e.* from events e where e.user = 'Jim' and '2014-10-09T09:05:00' >= e.entered and ('2014-10-09T09:05:00' <= e.exited or e.exited is NULL) or e.user = 'Jill' and '2014-10-10T09:10:00 >= e.entered and ('2014-10-10T09:10:00' <= e.exited or e.exited is NULL) or . . .; ``` SQL Ser...
Answers from Jonas and Gordon got me on track, I think. Here is query that seems to do the job: ``` CREATE TABLE #SEARCH_PARAMETERS(User VARCHAR(16), "Timestamp" DATETIME) INSERT INTO #SEARCH_PARAMETERS(User, "Timestamp") VALUES ('Jim', '2014-10-09T09:05:00'), ('Jim', '2014-10-10T09:01:00'), ('Jill', '2014-10-10T09...
SQL Query: Search with list of tuples
[ "", "sql", "sql-server", "" ]
I have a table in Hive with with 5 columns i.e. email, a\_first\_date, b\_first\_date, c\_first\_date, d\_first\_date. a, b, c, d are 4 different actions which a user can take and 4 columns in the table above indicate the date on which the user did the first respective action. For example, the value in **'a\_first\_da...
Why not use a case statement? This seems to have been thoroughly discussed in SQL here: <https://dba.stackexchange.com/questions/21542/what-is-the-most-efficient-way-to-get-the-minimum-of-multiple-columns-on-sql-ser>
Use the function least(). For example; Select \*, least(col1,col2,col3) as minofcol from Tablename;
Hive (Finding min of n columns in a row)
[ "", "sql", "hadoop", "hive", "" ]
Say I have a call ``` SELECT * FROM tablename WHERE id IN (5,3,8,9); ``` That returns the results in the id order of 3,5,8,9. Is there any way to get it to return the results in the given 5,3,8,9 order?
``` SELECT * FROM tablename WHERE id IN (5,3,8,9) ORDER BY CASE id WHEN 5 THEN 1 WHEN 3 THEN 2 WHEN 8 THEN 3 WHEN 9 THEN 4 ELSE 5 END ``` **[Fiddle](http://sqlfiddle.com/#!15/b27aa/1)**
Another option which is a bit more flexible because you only need to change the ids once. ``` with id_list (id, sort_order) as ( values (5,1), (3,2), (8,3), (9,4) ) select t.* from tablename join id_list l on l.id = t.id order by l.sort_order; ``` Maintaining the sort\_order is however somewhat ugly if you need t...
Is there a way to return SELECT results sorted by order of "WHERE IN" values?
[ "", "sql", "postgresql", "" ]
I have a table In MS SQL-Server which has hours in a `varchar` column. For ex. `'4:30'` (hr:Min). Basically it is a time span for an amount of work. Now I need the total sum of this column. How to convert it ? My table looks like this ``` Create table tblWrkingHors ( Id int primary key, name varchar(50), ...
A VARCHAR may not be the most efficient version of storing time, but with a bit of casting you can do what you're looking for; ``` WITH cte AS ( SELECT name, SUM(DATEDIFF(MINUTE, '00:00', CAST(WorkingHr AS TIME))) t FROM mytable GROUP BY name ) SELECT name, RTRIM(t/60) + ':' + RIGHT('0' + RTRIM(t%60), 2) FROM cte ...
[SQL Fiddle](http://sqlfiddle.com/#!6/2ec56/2) **MS SQL Server 2012 Schema Setup**: ``` CREATE TABLE Test_Table(Id INT, name VARCHAR(10), WorkingHr VARCHAR(8)) INSERT INTO Test_Table VALUES (1 ,'sam' ,'08:20'), (2 ,'sam' ,'04:50'), (3 ,'sam' ,'04:34'), (4 ,'Pam' ,'05:50'), (5 ,'sam'...
How to sum time spans stored in a varchar column?
[ "", "sql", "sql-server", "" ]
I have the following SQL Tables: companies: ``` ╔═════╦══════════╦═════════╦═══════════╦══════════════════╦═════╗ ║ # ║ Name ║ Country ║ City ║ Address ║ Nr. ║ ╠═════╬══════════╬═════════╬═══════════╬══════════════════╬═════╣ ║ 1 ║ T-Online ║ Germany ║ Frankfurt ║ Teststr. ║ 15 ║ ║ 2 ...
Well you can use JOIN and add index on country and city in companies table ``` SELECT Name FROM companies AS c INNER JOIN tagsForCompany AS tc ON c.id = tc.Company INNER JOIN tags AS t ON t.id = tc.TID WHERE city = "your_city" AND country = "your_country" AND t.Name REGEXP 'your_tag' ``` Well in this query a table wi...
try this ``` SELECT * FROM companies c, tags t, tagsForCompany tfc WHERE tfc.company = c.companyId AND t.ID = tfc.TID AND t.Name = 'Software Development' AND c.city = 'New York' AND c.Country = 'USA' ```
I cannot think of a valid SQL Query for solving this
[ "", "mysql", "sql", "performance", "" ]
I'd like to know an efficient way of taking event records with a start date and end date and basically replicating that record for each day between the start and end date So a record with a Start Date as 2014-01-01 and End Date as 2014-01-03 would become 3 records, one for each day I have a date table if that helps. ...
As you already have date table, You can JOIN your table with date table to get all dates to have same record as your start and end date ``` SELECT A.data, DT.startDate, DT.endDate FROM DateTable DT JOIN A ON A.StartDate >= DT.startDate And A.EndDate <= DT.endDate ```
use this query ``` declare @startDate datetime = getdate() declare @endDate datetime = dateadd(day,10,getdate()) ;with days as ( select @startDate as StartDate, @endDate as EndDate, @startDate as CurrentDate, 0 as i union all select d.StartDate, d.EndDate...
Converting 1 record with a start and end date into multiple records for each day
[ "", "sql", "sql-server", "t-sql", "" ]
I've problems join 4 mysql tables for my callmanagement. My tables are : ``` calls: callId | contactId | companyId | numberId | timestamp | callNote | duration | state contacts: contactId | firstName | lastName | companyId | email | contactNote numbers: numberId | contactId | number companies: companyId | companyN...
try this ``` select o.callId , o.timestamp , o.duration ,o.callNote , o.state,o.contactId, j.firstName , j.lastName ,j.company Id as company, j.email, j.contactNote, r.number from calls o left outer join contacts j on o.contactId =j.contactId left outer join numbers r on j.contactId=r.contactId; ```
You should use an `INNER JOIN` to join up the tables. For example: ``` SELECT c.callId, c.timestamp, c.duration, n.number, c.callNote, c.state, c.contactId, c1.firstName, c1.lastName, c2.CompanyName as company, c1.email, c1.contactNote FROM calls c INNER JOIN...
MySQL join 4 tables
[ "", "mysql", "sql", "database", "" ]
We have a working table that we build every night with over a million records. This procedure takes around 3 hours a night to complete. Within the `procedure` we insert all the data into the table first. Then we do a lot of updates to the table. For example: ``` Update a Set a.Field1 = b.Field1 From WorkingTable as a...
To answer this question, you need to first know how keys and indexes work under the hood in SQL server. A primary key, by default, is a clustered unique index. While this does slow down inserting records, the slowdown should be minimal. The real drop in performance usually comes from a `where` clause in a SQL query or...
It may run faster and it may not. That an index exists doesn't guarantee that it will be used. Let's say table2 in your example contains only two records. Then it would definitely make sense for the dbms to use an index on WorkingTable.id to find the two records quickly. Now let's say table2 contains 10000 times as m...
Should you put Indexes on a SQL Table that you are updating?
[ "", "sql", "sql-server", "" ]
I want to to select from db ``` if id=0 select * from tbl else select * from tbl where id= :id ``` how can use it in mysql query?
Try this: ``` select * from tbl where :id = 0 union all select * from tbl where :id <> 0 and id = :id ``` This is just a single query and it will execute only one branch as the specified `:id` value. When `:id=0`, the first query's where condition become `true` and the result is the same as `select * from tbl`. When ...
The difference between both your queries is just the `where` clause - you can express this with the `or` logical operator: ``` SELECT * FROM tbl WHERE (:id = id) OR (:id = 0) ``` Of course, this could be further cleaned up with the `in` operator: ``` SELECT * FROM tbl WHERE :id IN (id, 0) ```
how can write sql query statement with if-else
[ "", "mysql", "sql", "" ]
I have some data that I need to sum for each month and I am having trouble figuring out how to get it to have 12 columns (one for each month) with the sum total for that month. Example: Data as is: ``` GrossAmt ClaimDate 49764.00 2014-08-21 00:00:00.000 1382.43 2014-08-27 00:00:00.000 602.77 2014-09-0...
You need to use `PIVOT` to get the desired results CTE is doing the Monthly aggregation and PIVOT is used to convert the CTE result rows into horizontal columns ``` ;With CTE ([GrossAmt],MonthVal) AS( SELECT TOP 10000 Sum([GrossAmt]) as GrossAmt, DATEADD(MONTH, DATEDIFF(MONTH,0,ClaimDate), 0) as MonthV...
``` DECLARE @Cols NVARCHAR(MAX); SELECT @Cols = STUFF(( SELECT DISTINCT ', ' + QUOTENAME(DATENAME(MONTH,ClaimDate)) FROM TABLENAME FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,2,'') DECLARE @Sql NVARCHAR(MAX); SET @Sql = 'SELECT ''GrossAmount'' AS AMOUNT_Sorte...
Row over partition for totaling data by month
[ "", "sql", "t-sql", "window-functions", "" ]
While doing SSIS job I got an error in my create table query > Incorrect Syntax near '-' .(Microsoft SQL Server Native Client 10.0) SQL statement: ``` CREATE TABLE Staging_ACD_Precision_Queue ( PrecisionQueueID int, BucketIntervalID int, EnterpriseName varchar(32), AgentOrdering int, CallOrderin...
You need to put square brackets around `Partner-Center`, e.g. `[Partner-Center]`. Embedded spaces or special characters are not allowed in field names, but you can escape them by putting the field name within square brackets. ``` CREATE TABLE Staging_ACD_Precision_Queue ( PrecisionQueueID int, BucketIntervalID...
SQL Server does not allow `-` in bare field names. However, you can "escape" it by surrounding the field name with square brackets (`[]`): ``` CREATE TABLE Staging_ACD_Precision_Queue ( PrecisionQueueID int, BucketIntervalID int, EnterpriseName varchar(32), AgentOrdering int, CallOrdering int, ...
Incorrect Syntax near '-' .(Microsoft SQL Server Native Client 10.0)
[ "", "sql", "sql-server", "ssis", "syntax-error", "" ]
am working with a wordpress website that is performing the following query, but I see this query is doing many inner joins and the website takes long to load and goes down a lot, and I have been trying to create a query that produces the same result but with no success yet I would like to know what could be a better w...
It seems you are trying to obtain a result set with one row per post of type `car`. It seems you want to display various attributes of each car in the post, and those are stashed away in `postmeta`. Pro tip: **Never** use `SELECT *` in software unless you absolutely know why you're doing it. Especially with queries co...
This is a Wordpress database, and you might be reluctant to make extensive changes to the schema, because it could break other parts of the application or complicate upgrades in the future. The difficulty of this query shows one of the downsides to the [entity-attribute-value](/questions/tagged/entity-attribute-value ...
Improving a query using a lot of inner joins to wp_postmeta, a key/value table
[ "", "mysql", "sql", "database", "wordpress", "entity-attribute-value", "" ]
I have the following: ``` | Group_ID | Value | |----------|-------| | 146 | A | | 146 | B | | 239 | NULL | | 239 | F | | 826 | NULL | | 826 | NULL | ``` I need to retrieve only the IDs that have all related values null. In this example, the output would be `826`. I know t...
``` select group_id from t group by group_id having sum(case when value is null then 1 end)=count(*) ```
This should do it: ``` select t1.group_id from foo t1 group by t1.group_id having count(*) = (select count(*) from foo t2 where t2.group_id = t1.group_id and t2.value is null); ``` SQLFiddle example: <http://sqlfiddle.com/#!15/7d228/1>
Query to retrieve groups where all related values are null
[ "", "sql", "" ]
I have a `database1` which has more than 500 tables and I have `database2` which also has the same number of tables and in both the databases the name of tables are same.. some of the tables have different table definitions, for example a table `reports` in `database1` has 9 columns and the table `reports` in `database...
SSIS and SQL Server 2008 Wizards can be finicky tools. If you get a "can't insert into column ABC", then it could be one of the following: * Inserting into a PK column -> when setting up the mappings, you need to indicate to overwrite the value * Inserting into a column with a smaller range -> for example from nvarch...
If you're open to using tools then what about using something like [Red Gate Sql Compare](http://www.red-gate.com/products/sql-development/sql-compare/) and [Red Gate SQL Data Compare](http://www.red-gate.com/products/sql-development/sql-data-compare/)? First I would use data compare to manage the schema differences, ...
How can I copy and overwrite data of tables from database1 to database2 in SQL Server
[ "", "sql", "sql-server", "database", "sql-server-2008", "" ]
Many code editors have a built-in menu item or keyboard function to get a UUID, for example when I press `CTRL` + `SHIFT` + `G` in Delphi it inserts a GUID at the current position in the source code. I know that I can use `SELECT NEWID()` to generate a UUID, but I have to go to the query result, copy the generated UUI...
`NEWID()` itself is a function. when called returns a GUID value. You do not have to put it in a separate window and then copy paste value from there. Just simply put that function there where you want the GUID value and when the query is executed at run time the value returned by this function will be used. For inst...
For SQL server, and maybe others. One can insert a string-encoded Guid/uuid in SQL server using the convert function. See the zeroed Guid in the example below. ``` INSERT INTO [schema].[table] ([Id] ,[stuff]) VALUES (Convert(uniqueidentifier, N'00000000-0000-0000-0000-00000000000...
How to insert a NEWID() / GUID / UUID into the code editor?
[ "", "sql", "sql-server", "ssms", "" ]
Recently faced issues with how to know about deleted records from table. I try to explain my question. I have a table like below : **Table Employee** ``` Emp No Employee Name unique Guid1 John Smith unique Guid2 Tom unique Guid3 Jenny unique Guid4 Pa...
I see several options 1. **Modify the schema** (table definiation) to include fields like "isDeleted", "deletedOn", "deletedBy" and set these fields when "deleting" instead og actually deleteing the records. All "selects" from this table must then when altered to include this new logic 2. **Use a trigger** to listen t...
Change tracking feature is available for SQL Server 2008. See <http://msdn.microsoft.com/en-us/library/bb964713.aspx>
Find the deleted records in the Sql server 2008
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I'm working on the following query and table ``` SELECT dd.actual_date, dd.week_number_overall, sf.branch_id, AVG(sf.overtarget_qnt) AS targetreach FROM sales_fact sf, date_dim dd WHERE dd.date_id = sf.date_id AND dd.week_number_overall BETWEEN 88-2 AND 88 AND sf.branch_id = 1 GROUP BY dd.actual_date, branch_id, dd.w...
You want to use conditional aggregation: ``` with t as ( <your query here> ) select week_number_overall, sum(case when targetreach > 0 then 1 else 0 end) from t group by week_number_overall; ``` However, I would rewrite your original query to use proper `join` syntax. Then the query would look like: ``` S...
``` select sum( decode( sign( TARGETREACH ) , -1 , 0 , 0 , 0 , 1 , 1 ) ) from ( "your query here" ); ```
Counting number of positive value in a query
[ "", "sql", "oracle", "" ]
In below code I am trying to find time difference in minutes ``` declare @a time declare @b time select @a = "Apr 1, 2014 22:36.000" select @b = "Apr 2, 2014 02:25.000" select datediff(minutes,@a,@b) ``` **Expected output is 229 minutes. 24 min (60- 36) + 3 hour (180 min) + 25 min = 229 minutes** But **I am getting ...
You have declared the variables as time which cannot exceed 24 hours. The date portion is ignored. In effect you are sending this to the datediff functoon ``` datediff(minute,'22:36.000', '02:25.000') ``` and that is why you are getting a negative result. I suggest you declare @a and @b as datetime instead. ``` de...
You can use this query as reference to calculate time difference . ``` select DATEDIFF(day,2007-11-30,2007-11-20) AS NumberOfDays, DATEDIFF(hour,2007-11-30,2007-11-20) AS NumberOfHours, DATEDIFF(minute,2007-11-30,2007-11-20) AS NumberOfMinutes FROM test_table ```
Finding difference between time
[ "", "sql", "sybase", "" ]
How would I check if a particular word is contained in the text of a field in my dataset using R. In SQL, we can use the LIKE comparison operator. For example, ``` SELECT * FROM schools WHERE name LIKE '%Public School%' ``` If I had to do the same thing in R, how would I do that?
Given ``` schools <- data.frame(rank = 1:20, name = rep(c("X Public School", "Y Private School"), 10)) ``` try this: ``` subset(schools, grepl("Public School", name)) ``` or this: ``` schools[ grep("Public School", schools$name), ] ``` or this: ``` library(sqldf) sqldf("SELECT * FROM schools WH...
In Base R one can use %in% to subset data e.g. dataframe[dataframe$variable %in% dataframe2$variable2]
What is the R equivalent of SQL's "LIKE '%searched_word%'"?
[ "", "sql", "r", "" ]
Suppose that you have a table with the following structure: ``` CREATE TABLE [log] ( [type] int NOT NULL, [stat] nvarchar(20) NOT NULL, [id] int IDENTITY (1, 1) NOT NULL, descr nvarchar(20), PRIMARY KEY ([type], [stat], [id]) ) ``` Is it possible to force the `[id]` to be incremented only whenever the other...
No. The purpose of an IDENTITY (or SEQUENCE) is only to generate an incremental integer. There may be gaps as values are not reused, and values may be reserved but not used. You can use an expression in queries to show the desired value. ``` ROW_NUMBER() OVER (PARTITION BY type, stat ORDER BY id) AS Seq ```
This i think would get your job done ``` CREATE TABLE [LOG1] ( [TYPE] INT NOT NULL, [STAT] NVARCHAR(20) NOT NULL, [ID] INT , DESCR NVARCHAR(20), PRIMARY KEY ([TYPE], [STAT], [ID]) ) CREATE TRIGGER TR_LOG ON [DBO].[LOG1] INSTEAD OF INSERT AS BEGIN DECLARE @CNT INT=0 IF EXISTS(SELECT 'X' FROM LOG1 A JOIN INS...
T-SQL Unique Identity Column as Part of Composite Primary Key
[ "", "sql", "sql-server", "t-sql", "primary-key", "composite-primary-key", "" ]
I'm learning SQL and have been going through the chapters of the GalaXQL app. I've written the following query in answer to the question "Hilight the star (or stars) which has the planet with the highest orbit distance in the galaxy. Remember to clear the old hilights before beginning." This query returns the result ...
Alright let's start by looking at your base query. I know you already have an answer that works but I feel I need to explain to you what was going on in your query. ``` INSERT INTO hilight SELECT DISTINCT s.starid FROM planets AS p, stars AS s, moons AS m WHERE s.starid=( SELECT starid FROM p...
You could remove the first select such that it would liook like... ``` INSERT INTO hilight SELECT DISTINCT p.starid FROM planets p WHERE orbitdistance=( SELECT MAX(orbitdistance) FROM planets) ; ``` You could also remove the distinct, unless you had a specific reason for including it.
SELECT .. FROM (SELECT .. FROM ..). How can I improve this query?
[ "", "sql", "sqlite", "" ]
I imported a database for MSSQL 2008 for development. I know they have stored procedures because I was able to edit them live with the web interface front that they have. Now that I have the database loaded in a development location how do I access them? Are they normally stored in a table? I see at least one table wi...
Got it! So different from working with MySQL. 1. In Object Explorer, connect to an instance of Database Engine and then expand that instance. 2. Expand Databases, expand the database in which the stored procedure belongs, and then expand Programmability. 3. Expand Stored Procedures, right-click the procedure to...
Normally you would use SSMS - SQL Server Management Studio to do this. Its usually included with SQL Server, so you may just need to install it. <http://msdn.microsoft.com/en-us/library/ms174173.aspx> or download it here: <http://www.microsoft.com/en-us/download/details.aspx?id=7593>
Editing Stored Procedures in MSSQL Server 2008
[ "", "sql", "sql-server", "windows", "sql-server-2008", "stored-procedures", "" ]
I have the select query with `or` logical operator like following: ``` SELECT * FROM grabli_new.product where article like '%AV2%' or article like '%AV22%'; ``` I need to ordering result set by "length of like pattern"(rows that contains the longest pattern in my case `'%AV22%'` must be in the beginning of result set...
You can try to use something like this: ``` SELECT *, case when article like '%AV22%' then 1 when article like '%AV2%' then 2 end orderIndex FROM grabli_new.product where article like '%AV2%' or article like '%AV22%' order by orderIndex ```
if you want to count (multi-byte) characters, use the CHAR\_LENGTH function instead: ``` ORDER BY CHAR_LENGTH( column ) ```
MySQL "Order By" query
[ "", "mysql", "sql", "" ]
tbl\_chat: ``` message_id message_text users_id another_user time_sent 1 'hi' 9 1 2014-10-13 00:10:32 2 'hello' 1 9 2014-10-13 00:12:32 3 'good morning' 9 1 2014-10-13 00:12:34 4 'good n...
``` SELECT CONCAT_WS(' ',i.users_fname, i.users_lname) AS full_name, c.message_text,c.time_sent,c.message_id FROM tbl_chat AS c LEFT JOIN tbl_usersinfo AS i ON i.users_id = c.users_id WHERE (c.users_id = 1 AND c.another_user = 9) OR (c.users_id = 9 AND c.another_user = 1) ORDER BY time_sent ASC ```
There is a minor logic error ``` SELECT CONCAT_WS(' ',i.users_fname, i.users_lname) AS full_name, c.message_text,c.time_sent,c.message_id FROM tbl_chat AS c LEFT JOIN tbl_usersinfo AS i ON i.users_id = c.another_user // this is another user so turning 1 to 9 WHERE c.users_id = 1 UNION SELECT CONCAT_WS(' ',i.users_fna...
2 left joins with a union
[ "", "mysql", "sql", "" ]
I found some threads about the error. But all the solutions doesn't work for me. I created 2 tables a user table and one for articles. Now I want to store the user that created the article and the one who is the last modifier. ``` CREATE TABLE IF NOT EXISTS `testDb`.`users` ( `id` INT NOT NULL AUTO_INCREMENT, `ni...
`create_user INT UNSIGNED ZEROFILL` cannot reference `id INT`, because these count as different data types for purposes of foreign key reference. Make them the same data type. The only data type difference that is permitted between columns in a foreign key relationship is length of a varchar. For example, VARCHAR(10) ...
I came across this issue and my Data Type was correct so I was stumped for a little but then I just made everything the same. When creating foreign keys be sure the columns you are using have the same: * Data Type * Collation * Zero Fill * Not Null * Unsigned * Binary
Error Code: 1822. Failed to add the foreign key constaint. Missing index for constraint
[ "", "mysql", "sql", "foreign-keys", "" ]