Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I need help with this Conversion failed when converting date and/or time from character string. I'm trying to run a simple query on an @as\_of\_date, 10 days ago and 30 days ago. The query works fine if I run it on 3-5 accounts, but any more than that if fails. How do I change my query so that I don't get the conversi...
You can try using ISDATE function to see the input data is a valid date.. Also I don't see in the screenshot how/what is the input.
You are converting the `@as_of_date` twice. You can use `SELECT convert(date, getdate(), 110)` Correct me if I am wrong.
tsql - Conversion failed when converting date and/or time from character string
[ "", "sql", "sql-server", "t-sql", "" ]
Why do we need to have two tables (master and transaction table) of any topic like `sales`,`purchase`,etc.. What should be the relationship between the two tables and what should be the difference between them. Why do we really need them.
Master and Transaction tables are needed in the database schema specially in the verticals of sales. **Master Data**: Data which seldom changes. For example, if a company has a list of 5 customer then they will maintain a customer master table having the name and address of the customers alongwith other data which wil...
In the end, it really depends on the type of data you are working with. If you have a specific example, that might give us a better indication on what you are trying to do. However, in general, a master table would theoretically be constant in relationship to habitual changes seen in your transaction table.
difference between master and transaction table
[ "", "sql", "sql-server", "database", "" ]
I want to get the latest highscore, per user, per game. My current query isn't working. I have a SQL DB like the following: ``` player(string) game(string) score(int) Date(Date) time(Time) jake soccer 20 2016/02/26 10:00:00 jake chess 50 2016/0...
To get the latest highscore, per user, per game, try this: ``` ;WITH cte as ( SELECT player, game, MAX(convert(datetime,cast([date] as nvarchar(10)) + ' '+ cast([time] as nvarchar(10)))) TS FROM db GROUP BY player, game) SELECT db.* FROM cte LEFT JOIN db ON cte.player = db.player and cte.game = db.game and cte....
Try using ROW\_NUMBER() ``` SELECT t1.* FROM ( SELECT * , ROW_NUMBER() OVER (PARTITION BY player ORDER BY [time] DESC) AS rn FROM db ) AS t1 WHERE rn = 1 ; ```
Using MAX(Time) and MAX(Date) to get only the latest per group
[ "", "sql", "sql-server", "" ]
I have a XML column that is not generated with a namespace, meaning no xmlns attribute. Unfortunately, I cannot fix the actual problem, meaning where the XML is created. For example: ``` <root>Our Content</root> ``` I *can* modify the XML data before it's returned to a particular client that expects a namespace. Wha...
Maybe as simple as this? ``` DECLARE @xml XML='<root>Our Content</root>'; SELECT CAST( REPLACE(CAST(@xml AS NVARCHAR(MAX)),'<root>','<root xmlns="http://OurNamespace">') AS XML) ```
Best alternative I could come up with, select root subnodes and place it between `<root xmlns="http://OurNameSpace">...</root>`. ``` DECLARE @t TABLE(e XML); INSERT INTO @t(e)VALUES('<root><el1>Our Content</el1></root>'); INSERT INTO @t(e)VALUES('<root><el2>Our Content</el2></root>'); SELECT '<root xmlns="http://...
How to add or change an Xml namespace in SQL Server / Cannot use 'xmlns' in the name expression
[ "", "sql", "sql-server", "xml", "xml-namespaces", "" ]
I need to return `true` or `false` rather than `1` & `0`, using following query: ``` select if(u.id is null,false,true) status from user u limit 10 ``` the above query returns `status` with value 0 or 1 rather than `true` and `false`, Is there any way to fix this?
If you want, you can return the values as *strings*: ``` SELECT IF(u.id IS NULL, 'false', 'true') as status FROM user u LIMIT 10 ```
TRUE/FALSE is equivalent to 1/0. It's just a matter of how your front end displays it. If you need to return the strings "true" and "false" (which I don't suggest - handle that in the display) then you'll have to account for that as well: `IF(IF(u.id ISNULL,false,true) = 1, 'TRUE', 'FALSE')`
MySQL: return "0" & "1" rather than "false" & "true"
[ "", "sql", "" ]
I am curious about the logical query processing phase of SQL queries. For `SELECT` queries, the logical query processing phase order is: 1. FROM 2. ON 3. OUTER 4. WHERE 5. GROUP BY 6. CUBE | ROLLUP 7. HAVING 8. SELECT 9. DISTINCT 10. ORDER BY 11. TOP What is the order for `INSERT`, for `UPDATE` and for `DELETE`?
If you would like to know what the actual query processing order is, take a look at the execution plan. That will tell you step by step exactly what SQL Server is doing. <https://technet.microsoft.com/en-us/library/ms178071(v=sql.105).aspx>
**SQL Server: [Source](https://msdn.microsoft.com/en-us/library/ms189499.aspx "Source")** 1. FROM 2. ON 3. JOIN 4. WHERE 5. GROUP BY 6. WITH CUBE or WITH ROLLUP 7. HAVING 8. SELECT 9. DISTINCT 10. ORDER BY 11. TOP
Logical query processing phase of INSERT, DELETE, and UPDATE in SQL queries
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I wanna get all my articles out of my database where the date of the last update is greater than the publishing date + 1 week. Do you habe an idea how that should work? In my table there is the `publish_date` and the `update_date`. Both of them contain a datetime in the following format: `Y-m-d H:i:s` It should be so...
``` SELECT * FROM foo WHERE update_date > DATE_ADD(publish_date, INTERVAL 1 WEEK) ``` See [MySQL DATE\_ADD](http://www.w3schools.com/sql/func_date_add.asp).
If you want to retain your structure (i.e. not use a DATE\_ADD function), I would use: ``` SELECT * FROM foo WHERE update_date > publish_date + INTERVAL 1 WEEK ```
How to get data out of a database where the saved date is greater than another date + 1 week
[ "", "mysql", "sql", "" ]
How do I retrieve results for not used positions in my database. Here is an example: ``` TABLE POSITION PosID PosName 101 President 102 Vice President 103 Secretary 104 Treasurer 105 Auditor 106 Srgt of Arms TABLE OFFICER OfficerID OrganizationID Name PosID (FK to TABLE POSITI...
You can use `NOT EXISTS`: ``` SELECT * FROM POSITION WHERE NOT EXISTS (SELECT 1 FROM OFFICER WHERE OrganizationID = '2016-02081-0' AND OFFICER.PosID = POSITION.PosID); ``` The above query returns all `POSITION` records not being related to an `OFFICER` r...
You could use the `not in` operator: ``` SELECT PosID FROM position WHERE PosID NOT IN (SELECT PosID FROM officer) ``` Or the `not exists` operator: ``` SELECT PosID FROM position p WHERE NOT EXISTS (SELECT * FROM officer o WHERE p.PosId = o.PosI...
database - retrieve results for unused positions
[ "", "mysql", "sql", "database", "select", "database-design", "" ]
My database looks like: **Table: dept\_emp**: ``` +--------------------------+-----------------------+------------------------+ | emp_no (Employee Number) | from_date (Hire date) | to_date (Worked up to) | +--------------------------+-----------------------+------------------------+ | 5 | 1995-...
You could try something like this: ``` select d.*, datediff( case when to_date = '9999-01-01' then current_date else to_date end, from_date) as how_long from dept_emp d where datediff( case when to_date = '9999-01-01' then current_date else to_date end, from_date) = ( -- find the longest tenur...
Firstly I would suggest to make that to\_date DEFAULT NULL. You want to have NULL there, if employee is still working, no need for 9999- stuff. Now, to your question about longest working employee. You could calculate the date difference like this, accounting for NULL to be today's date: ``` SELECT emp_no, MAX(DATEDI...
Select longest working employee in SQL
[ "", "mysql", "sql", "" ]
For the following tables: **ROOM** ``` +----+--------+ | ID | NAME | +----+--------+ | 1 | ROOM_1 | | 2 | ROOM_2 | +----+--------+ ``` **ROOM\_STATE** ``` +----+---------+------+------------------------+ | ID | ROOM_ID | OPEN | DATE | +----+---------+------+------------------------+ | 1 | ...
In Postgres, I would recommend `distinct on`: ``` select distinct on (rs.room_id) r.name, rs.* from room_state rs join room r on rs.room_id = r.id order by rs.room_id, rs.date desc; ``` `distinct on` is specific to Postgres. It guarantees that the results have only one row for each room (which is what you w...
You can use the following query: ``` SELECT R.ID, R.NAME FROM ROOM AS R INNER JOIN ROOM_STATE AS RS ON R.ID = RS.ROOM_ID AND RS.OPEN = 1 LEFT JOIN ROOM_STATE AS RS2 ON R.ID = RS2.ROOM_ID AND RS2.OPEN = 0 AND RS2.DATE > RS.date WHERE RS2.ID IS NULL ``` [**Demo here**](http://sqlfiddle.com/#!9/68e8bf/21) This will re...
Where clause on joined table
[ "", "sql", "postgresql", "" ]
I am trying to calculate in a SQL statement. I am trying to calculate the total amount in the `invoice.total` column per customer. I created the following statement: ``` SELECT customers.firstname, customers.lastname, customers.status, SUM(invoice.total) AS total FROM customers INNER JOIN invoice ON customers.id=invo...
First, you need to Group the data when you want to have aggregate results: ``` SELECT customers.firstname, customers.lastname, customers.status, SUM(invoice.total) AS total FROM customers INNER JOIN invoice ON customers.id=invoice.id GROUP BY customers.firstname, customers.lastname, customers.status; ``` Second,...
You have to add a group by customer (id property for example). If you want to have first and last name in select then you will have to group by them as well.
Calculate in SQL with Inner Join
[ "", "mysql", "sql", "" ]
In my project I need to query the db with pagination and provide user the functionality to query based on current search result. Something like limit, I am not able to find anything to use with nodejs. My backend is mysql and I am writing a rest api.
You could try something like that (assuming you use [Express](http://expressjs.com/) 4.x). Use GET parameters (here page is the number of page results you want, and npp is the number of results per page). In this example, query results are set in the `results` field of the response payload, while pagination metadata ...
I taked the solution of @Benito and I tried to make it more clear ``` var numPerPage = 20; var skip = (page-1) * numPerPage; var limit = skip + ',' + numPerPage; // Here we compute the LIMIT parameter for MySQL query sql.query('SELECT count(*) as numRows FROM users',function (err, rows, fields) { if(err) { ...
Pagination in nodejs with mysql
[ "", "mysql", "sql", "node.js", "pagination", "limit", "" ]
I need to alter the physical structure of a table. Combine 2 columns into a single column for the entire table. E.g ``` ID Code Extension 1 012 8067978 ``` Should be ``` ID Num 1 0128067978 ```
You can just add them together in the select statement: ``` SELECT Column1 + Column2 AS 'CombinedColumn' FROM TABLE ``` To Permanently Add them together: Step 1. [Add Column](https://msdn.microsoft.com/en-us/library/ms190238.aspx): ``` ALTER TABLE YOUR_TABLE ADD COLUMN Combined_Column_Name VARCHAR(15) NULL ...
``` ALTER TABLE DataTable ADD FullNumber VARCHAR(15) NULL GO UPDATE DataTable SET FullNumber = ISNULL(Column1, '') + ISNULL(Column2, '') GO -- you may have FullNumber as NOT NULL, if the number is mandatory and not null for every record ALTER TABLE DataTable ALTER COLUMN FullNumber VARCHAR(15) NOT NULL ``` First st...
Alter table merge columns T-SQL
[ "", "sql", "sql-server", "t-sql", "" ]
I have a table in MySQL that I need to join with a couple of tables in a different server. The catch is that these other tables are in Informix. I could make it work by selecting the content of a MySQL table and creating a temp table in Informix with the selected data, but I think in this case it would be too costly. ...
What I ended up doing is manually (that is, from the php app) keeping in sync the mysql tables with their equivalents in informix, so I didn't need to change older code. This a temporary solution, given that the older system, which is using informix, is going to be replaced.
I faced a similar problem a number of years ago while developing a Rails app that needed to draw data from both an Informix and a MySQL database. What I ended up doing was using of an ORM library that could connect to both databases, thereby abstracting away the fact that the data was coming from two different database...
Joining MySQL and Informix tables
[ "", "mysql", "sql", "database", "join", "informix", "" ]
I haved saved SELECT query. I need create update query to update table field with value from saved select query. Im getting error "Operation must use an updatable query". Problem is that saved select query result not contain primary key. ``` UPDATE [table] INNER JOIN [saved_select_query] ON [table].id_f...
Perhaps a [DLookUp()](https://support.office.com/en-us/article/DLookup-Function-8896cb03-e31f-45d1-86db-bed10dca5937) will do the trick: ``` UPDATE [table] SET [target_field] = DLookUp("source_field", "saved_select_query", "my_field=" & id_field) ``` ... or, if the joined field is text ... ``` UPDATE [table] SET...
I'm not sure I completely understand what you are asking. If you are asking what syntax to use when performing an update with an inner join. ``` UPDATE tableAlias SET Column = Value FROM table1 as tableAlias INNER JOIN table2 as table2Alias on tableAlias.key = table2Alias.key ```
UPDATE query with inner joined query
[ "", "sql", "ms-access", "inner-join", "" ]
I'm working on products filter (faceted search) like Amazon. I have a table with properties (color, ram, screen) like this: ``` ArticleID PropertyID Value --------- ---------- ------------ 1 1 Black 1 2 8 GB 1 3 15" 2 1 White 2 2 ...
I made a snippet showing the lines along which I would work. Good choice of indices is important to speed up queries. Always check the execution plan for tweaking of indices. Notes: * The script uses temporary tables, but in essence they're not different from regular tables. Except for `#select_properties`, the tempo...
`intersect` is likely to work very well. An alternative approach is to construct a `where` clause and use aggregation and `having`: ``` SELECT ArticleID FROM ArticlesProperties WHERE ( PropertyID = 2 AND Value IN ('4 GB', '8 GB') ) OR ( PropertyID = 3 AND Value IN ('13"') ) GROUP BY ArticleId HAVING COUNT(DISTI...
SQL Server query by column pair
[ "", "sql", "sql-server", "faceted-search", "" ]
1) Table1 say table1 with structure as : `moduleID | moduleName 10 | XYZ 20 | PQR 30 | ABC` 2) Table2 say table2 with structure as : `moduleID | Level | Value 10 | 1 | 20 10 | 2 | 30 30 | 3 | 40 10 | 3 | 50 20 | 2 | 30` `moduleID` being primary key in table1,and value of the column `level` can have values 1 to 3. ...
You can use *conditional aggregation*: ``` select t1.moduleID, t1.moduleName, MAX(CASE WHEN Level = 1 THEN Value END) Level1, MAX(CASE WHEN Level = 2 THEN Value END) Level2, MAX(CASE WHEN Level = 3 THEN Value END) Level3 from table1 as t1 left join table2 as t2 on t1.moduleID = t2.moduleID group b...
Refer this all process it will work fine for your expected answer. ``` CREATE TABLE Table1 (moduleName VARCHAR(50),moduleID INT) GO --Populate Sample records INSERT INTO Table1 VALUES('.NET',10) INSERT INTO Table1 VALUES('Java',20) INSERT INTO Table1 VALUES('SQL',30) CREATE TABLE Table2 (moduleID INT,[Level] INT,Valu...
Select from two tables based on values of one of the table
[ "", "mysql", "sql", "" ]
[![enter image description here](https://i.stack.imgur.com/4NXhl.png)](https://i.stack.imgur.com/4NXhl.png) The problem is :Find the employee last names for employees who do not work on any projects. My solution is: ``` SELECT E.Lname FROM EMPLOYEE E WHERE E.Ssn NOT IN (SELECT * FROM EMPLOYEE E...
Try this ``` SELECT EMPLOYEE.Lname FROM EMPLOYEE WHERE EMPLOYEE.SSN NOT IN (SELECT DISTINCT WORKS_ON.Essn FROM WORKS_ON); ```
The result of a NOT IN subquery must be one value. Your subquery returns all the columns in the `EMPLOYEE` and `WORKS_ON` tables. You can use NOT EXISTS instead: ``` SELECT E.Lname FROM EMPLOYEE E WHERE NOT EXISTS (SELECT 1 FROM WORKS_ON W WHERE E.Ssn = W.Essn); ``` The `1` could...
MySQL: using "NOT IN" clause correctly
[ "", "mysql", "sql", "database", "" ]
I Have a long query which is throwing an exception when i execute. Query: ``` SELECT HostID,HostName,RackID,HostTypeID,DomainName,RackNumberOfHeightUnits,RackStartHeightUnits FROM tHosts, tDomains WHERE tHosts.DomainID=tDomains.DomainID AND (RackID IN ( SELECT tRacks.Name,tRacks.RackID,tRacks.SiteID,tRacks.Descrip...
With `IN` You must return one column, the column you want to compare against: Change this ``` ...AND (RackID IN ( SELECT tRacks.Name,tRacks.RackID,tRacks.SiteID,tRacks.Description,NumberOfHeightUnits FROM tDomains, tSites, tRacks ... ``` To this: ``` ... AND (RackID IN ( SELECT tRacks.RackI...
I think you should re-look at your SQL and determine exactly why you think you need to write the query in the way you have, not only for your own sanity when debugging it, but because it seems that you could simplify this query a great deal if there was a little more understanding of what was going on. From your SQL i...
Introduce sub query with EXISTS
[ "", "sql", "sql-server", "exists", "" ]
I have a table with FirstName and LastName. ``` FirstName LastName John Smith John Taylor Steve White Adam Scott Jane Smith Jane Brown ``` I want to select LastName that does not contain "Smith". If it matchs, don't use any of the same FirstName Output Result ``` FirstName...
You can do this with `not exists`: ``` select p.* from tablPerson p where not exists (select 1 from tablPerson p2 where p2.LastName = 'Smith' and p2.FirstName = p.FirstName ); ``` I prefer `not exists` for this type of query because it has more intuitive behavior i...
You need to use a sub query to filter out all the persons whose last name contains Smith, as mentioned below: ``` select first_name, last_name from person where first_name not in ( select first_name from person where last_name like '%Smith%'); ``` Here's the example [SQL Fiddle](http://sqlfiddle.com/#!9/2b250/2/0).
SQL Select First Name and Doesn't Contain Last Name Matching
[ "", "mysql", "sql", "" ]
It seems i can't figure how to swap two bites of a varchar with eachother in a string . Example : `string : 6806642004683587 (varchar)` `end : 8660460240865378` It should work like this : 68 06 64 20 04 68 35 87 and flip them like 86 60 46 ... Is there a function in sql that does bcd string manipulation ? Thank you
You could wrap this in a function, but here's the basic code: ``` DECLARE @VAL NVARCHAR(16) = N'6806642004683587'; DECLARE @OUT NVARCHAR(16); ;WITH A(N, S) AS ( SELECT 1 N, SUBSTRING(@VAL, 1, 2) S UNION ALL SELECT N+2 N, SUBSTRING(@VAL, N+2, 2) S FROM A WHERE N+2 < LEN(@VAL) ) SELECT @OUT = COALESCE(@OUT...
Can use a `while` loop. **Query** ``` declare @str as varchar(max); declare @len as int; declare @i as int; declare @ii as int; declare @res as varchar(max); declare @res1 as varchar(max); set @str = '6806642004683587'; set @len = len(@str) / 2; set @i = 1; set @ii = 1; set @res = ''; while @len >= @i begin set ...
mssql bcd string manipulation - swap 2 digits in a string
[ "", "sql", "sql-server", "t-sql", "" ]
I've got a **date** field. **For example :** ``` 01/03/2016 09:40:35 ``` I would like to know if this date is from **Today**.
`01/03/2016 09:40:35` is not a date, it is displayed in a format you want to see. It will be a date if you convert it using **TO\_DATE**. To know if the date part is current date, you need to compare it with **SYSDATE**. For example, ``` SQL> SELECT 2 CASE 3 WHEN TRUNC(to_date('01/03/2016 09:40:35', 'dd/...
You can compare your date value with `TRUNC(SYSDATE)` or `TRUNC(SYSTIMESTAMP)`, for example.
Know if a date is from today in Oracle
[ "", "sql", "oracle", "date", "" ]
I have 24 h time stored as `last_time` in database and I need to get the difference between current time and `last_time` in minutes. I have searched a lot but in all occasions time difference is taken by by two dates. Please tell me how to use `DiffDate` function correctly using 24 h formatted time.
For time difference is minutes ``` SELECT DATEDIFF(mi, last_time, CAST(getdate() as time)) from <TABLE_NAME> ``` For time difference in DD:MM:SS ``` declare @null time SET @null = '00:00:00'; SELECT DATEADD(SECOND, - DATEDIFF(SECOND, last_time, CAST(getdate() as time)), @null) from <TABLE_NAME> ``` For MYSQL ``` S...
Try this: ``` SELECT DATEDIFF(mi, last_time, CONVERT(varchar(10), GETDATE(), 108)) ```
How to take time difference in minutes from SQL Server using 24 hour time?
[ "", "mysql", "sql", "" ]
I have an XML file that I am passing into a stored procedure. I also have a table. The table has the columns VehicleReg | XML | ProcessedDate My XML comes in like so: ``` <vehicles> <vehicle> <vehiclereg>AB12CBE</vehiclereg> <anotherprop>BLAH</anotherprop> </vehicle> <vehicle> <vehiclereg>AB12CBE<...
Full query as you want: ``` DECLARE @XmlData XML Set @XmlData = '<vehicles> <vehicle> <vehiclereg>AB12CBE</vehiclereg> <anotherprop>BLAH</anotherprop> </vehicle> <vehicle> <vehiclereg>AB12CBE</vehiclereg> <anotherprop>BLAH</anotherprop> </vehicle> </vehicles>' SELECT T.Vehicle.value('./vehicle...
Just need to remember XML is case sensitive. You had: ``` FROM @XmlData.nodes('Vehicles/Vehicle') AS T(Vehicle) ``` but you should have had: ``` FROM @XmlData.nodes('/vehicles/vehicle') AS T(Vehicle) ``` Also as TT pointed out there was no column named `Registration` This should do it: ``` DECLARE @XmlData XML Se...
Insert XML Node into a SQL column in a table
[ "", "sql", "sql-server", "xml", "" ]
Is possible to select a numerical series or date series in SQL? Like create a table with N rows like 1 to 10: ``` 1 2 3 ... 10 ``` or ``` 2010-01-01 2010-02-01 ... 2010-12-01 ```
If you install [common\_schema](https://common-schema.googlecode.com/svn/trunk/common_schema/doc/html/introduction.html), you can use the `numbers` table to easily create queries to output those types of ranges. For example, these 2 queries will produce the output from your examples: ``` select n from common_schema....
An SQL solution: ``` SELECT * FROM ( SELECT 1 as id UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 ) ```
Is somehow possible to create select a series in mysql?
[ "", "mysql", "sql", "date", "range", "" ]
I have a query based on a date with get me the data I need for a given day (lets say sysdate-1): ``` SELECT TO_CHAR(START_DATE, 'YYYY-MM-DD') "DAY", TO_CHAR(TRUNC(MOD(ROUND(AVG((END_DATE - START_DATE)*86400),0),3600)/60),'FM00') || ':' || TO_CHAR(MOD(ROUND(AVG((END_DATE - START_DATE)*86400),0),60),'FM00') "DURATIO...
While bastihermann gave you the query to get all of those values in a single result set, if you want to understand the issue with your pl/sql block, the following should simplify it for you. The error relates to the fact that, in pl/sql you need to select INTO local variables to contain the data for reference within th...
First you need a "date generator" ``` select trunc(sysdate - level) as my_date from dual connect by level <= sysdate - to_date('10-10-2015','dd-mm-yyyy') MY_DATE ---------- 2016/02/28 2016/02/27 2016/02/26 .... .... 2015/10/12 2015/10/11 2015/10/10 142 rows selected ``` an then you need to plug this genera...
Loop query with a variable in Oracle
[ "", "sql", "oracle", "plsql", "" ]
I retrieve data by joining multiple tables as indicated on the image below. On the other hand, as there is no data in the FK column (EmployeeID) of Event table, I have to use CardNo (nvarchar) fields in order to join the two tables. On the other hand, the digit numbers of CardNo fields in the Event and Employee tables ...
Many thanks all of your help. With the help of your answers, I managed to reduce the query execution time from 2 minutes to 1 at the first step after using computed columns. After that, when creating an index for these columns, I managed to reduce the execution time to 3 seconds. Wow, it is really perfect :) Here are ...
You can add a computed column to your table like this: ``` ALTER TABLE TEmployee -- Don't start your table names with prefixes, you already know they're tables ADD CardNoRight8 AS RIGHT(CardNo, 8) PERSISTED ALTER TABLE TEvent ADD CardNoRight8 AS RIGHT(CardNo, 8) PERSISTED CREATE INDEX TEmployee_CardNoRight8_IDX ON T...
What if the column to be indexed is nvarchar data type in SQL Server?
[ "", "sql", "sql-server", "sql-server-2008", "join", "indexing", "" ]
I am currently learning sqlite and I've been working with sqlite manager so far. I have different tables and want to select all Project Names where 3 or more people have worked on. I have my project table which looks like this: ``` CREATE TABLE "Project" ("Project-ID" INTEGER PRIMARY KEY NOT NULL , "Name" TEXT, "Ye...
Try this: ``` SELECT t1.Project-ID, t1.Name FROM Project AS t1 JOIN ( SELECT Project-ID FROM Works_on GROUP BY Project-ID HAVING COUNT(*) >= 3 ) AS t2 ON t1.Project-ID = t2.Project-ID ```
You need join and group by with a having clause like this: ``` SELECT t.project-id,t.name FROM project t INNER JOIN works_on s ON(t.project-id = s.project-id) GROUP BY t.project-id,t.name HAVING COUNT(*) > 2 ```
SQLite Query Display Name with WHERE condition - Multiple Tables
[ "", "sql", "sqlite", "" ]
I'm practicing some SQL and I have to retrieve from the database all the information about employees whose (sal+comm) > 1700. I know this can be done with a simple WHERE expression, but we are practicing the CASE statement, so we need to do it that way. I already know how regular CASE works to assign a new row values ...
``` SELECT * FROM emp WHERE (CASE WHEN (sal+comm) > 1700 THEN 1 ELSE 0 END) = 1 ```
the `CASE` statement will produce a result and you can compare it or use it on other operations. In this case the salary depend on emp.job ``` SELECT * FROM emp WHERE CASE WHEN emp.job = 'DEVELOPER' THEN salary*1.5 WHEN emp.job = 'DB' THEN salary*2 END > 1700 ``` To solve your case is overkill but I...
SQL select rows conditionally using CASE expression
[ "", "sql", "oracle", "case", "" ]
I have a complex SQL query that can be simplified to the below: ``` Select ColA,ColB,ColC,ColD From MyTable Where (ColA In (Select ItemID From Items Where ItemName like '%xxx%') or ColB In (Select ItemID From Items Where ItemName like '%xxx%')) ``` As you can see, the sub-query appears twice. Is the compiler int...
### UPDATE Your request not to change the query, just the `WHERE` You can pack the CTE directly in the place where it is called (untested): ``` Select ColA,ColB,ColC,ColD From MyTable Where EXISTS (SELECT 1 FROM (Select i.ItemID From Items AS i Where iItemNa...
You can also write the query like this: ``` SELECT ColA, ColB, ColC, ColD FROM MyTable WHERE EXISTS( (SELECT ItemID FROM Items WHERE ItemName LIKE '%xxx%') INTERSECT SELECT t.v FROM (VALUES (ColA), (ColB)) AS t(v) ) ```
Remove duplicate sub-query
[ "", "sql", "sql-server", "t-sql", "common-table-expression", "dynamic-sql", "" ]
I'm using the below query to replace the value 2 with 5. My input string will be in the format as shown below. Each value will be delimited with carrot(^) symbol. It's working fine when there is no duplicate value. But with duplicate values it's not working. Please advice. ``` select regexp_replace('1^2^2222^2','(^|\^...
As others have said, the problem is the terminating delimiter caret being consumed matching the first occurrence, so it isn't seen as the opening delimiter for the next instance. If you don't want to use nested regex calls, you could use a simple replace to double up the delimiters, then strip them afterwards: ``` re...
### problem The problem is that the second adjacent occurrences of the searched string is not matched. This is because of the first portion of the regex: ``` (^|\^)2(\^|$) ^ -- this is not matched when the text preceding "2" is a replaced string ``` ### solution One way to solve your problem is to run the regex t...
Regarding Regexp_replace - Oracle SQL
[ "", "sql", "oracle", "oracle11g", "regexp-replace", "" ]
I have below table with 2 columns, DATE & FACTOR. I would like to compute cumulative product, something like CUMFACTOR in SQL Server 2008. Can someone please suggest me some alternative.[![enter image description here](https://i.stack.imgur.com/NNYMj.jpg)](https://i.stack.imgur.com/NNYMj.jpg)
Unfortunately, there's not `PROD()` aggregate or window function in SQL Server (or in most other SQL databases). But you can emulate it as such: ``` SELECT Date, Factor, exp(sum(log(Factor)) OVER (ORDER BY Date)) CumFactor FROM MyTable ```
You can do it by: ``` SELECT A.ROW , A.DATE , A.RATE , A.RATE * B.RATE AS [CUM RATE] FROM ( SELECT ROW_NUMBER() OVER(ORDER BY DATE) as ROW, DATE, RATE FROM TABLE ) A LEFT JOIN ( SELECT ROW_NUMBER() OVER(ORDER BY DATE) as ROW, DATE, RATE FROM TABLE ) B ON A.ROW + 1 = B.ROW ```
How to compute cumulative product in SQL Server 2008?
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Long time reader, first time poster. I'm trying to consolidate a table I have to the rate of sold goods getting lost in transit. In this table, we have four kinds of products, three countries of origin, three transit countries (where the goods are first shipped to before being passed to customers) and three destinatio...
Something like this? ``` select product ,sum(case when status = 'Delivered' then count else 0 end) as delivered ,sum(case when status = 'Not Delivered' then count else 0 end) as not_delivered ,origin ,transit ,destination from table group by product ,origin ,transit ,destination ```
This is rather easy; instead of one line per Product, Origin, Transit, Destination and Status, you want one result line per Product, Origin, Transit and Destination only. So group by these four columns and aggregate conditionally: ``` select product, origin, transit, destination, sum(case when status = 'Delivered...
Joining a Table with Itself with multiple WHERE statemetns
[ "", "sql", "google-bigquery", "" ]
I have two tables of service providers, `providers` and `providers_clean`. `providers` contains many thousands of providers with very poorly formatted data, `providers_clean` only has a few providers which still exist in the 'dirty' table as well. I want the system using this data to remain functional while the user i...
You need to do an outer join from Dirty to Clean (since Dirty has all rows Clean has, but not vice versa) ``` SELECT dirty.id AS id, CASE WHEN clean.id IS NOT NULL THEN clean.name ELSE dirty.name END AS new_name FROM dirty LEFT JOIN clean ON clean.id = dirty.id ORDER BY dirty.id asc ``` [Example](http://sqlfi...
Seems like a `LEFT JOIN` is what you need: ``` SELECT COALESCE(pc.ID, p.ID), COALESCE(pc.Name, p.Name) FROM providers AS p LEFT JOIN providers_clean AS pc ON p.ID = pc.ID ``` What this query essentially does: if the record exists in the 'clean' table then select this one, otherwise select the one from the 'dirty' tab...
Select rows from two tables and exclude primary keys that exist in both tables
[ "", "mysql", "sql", "database", "" ]
Here is the situation. I have two parameters to query: Item\_code Item\_type The first\_table contains: Item\_Code,Item\_Characteristics The second\_table contains: Item\_Type,Item\_Characteristics My goal is to get the item\_characteristics. If the specific item is not found in the first table, I would want to use ...
One way of doing this uses `not exists`: ``` select t1.Item_Characteristics from t1 where t1.item_code = @Item_Code union all select t2.Item_Characteristics from t2 where t2.item_type = @Item_Type and not exists (select 1 from t1 where t1.item_code = @Item_Code); ```
You can try with a `FULL JOIN` in case `Item_Code` and `Item_Type` are of the same type: ``` SELECT COALESCE(t1.Item_Characteristics, t2.Item_Characteristics) AS Item_Characteristics FROM table1 AS t1 FULL JOIN table2 AS t2 ON t1.Item_Code = t2.Item_Type WHERE COALESCE(t1.Item_Code, t2. Item_Type) = @param ```
Select from another table if record not found in the first table - SQL Server 2012
[ "", "sql", "sql-server", "t-sql", "" ]
I create an index `createdate_idx` on field `createdate`, then make this query: > select \* from tablename where createdate>=to\_date('2016-02-29','yyyy-mm-dd'); But I am not sure whether the index `createdate_idx` has been used or not. So How can I make this confirm?
[`EXPLAIN PLAN`](https://docs.oracle.com/cd/B19306_01/server.102/b14211/ex_plan.htm#g42231) will show you what index is used and other information. For example: ``` explain plan for select * from tablename where createdate>=to_date('2016-02-29','yyyy-mm-dd'); select * from table(dbms_xplan.display); Plan hash value...
Index status can be checked with query to Oracle system view: ``` select TABLE_NAME, INDEX_NAME, STATUS from USER_INDEXES where TABLE_NAME like '%'; ``` Value `N/A` for the `STATUS` field means that index is partitioned. Individual index partitions' status can be checked with this query: ``` select INDEX_NAME, PARTI...
Oracle:How to check index status?
[ "", "sql", "oracle", "indexing", "" ]
I have columns such as pagecount, convertedpages and changedpages in a table along with many other columns. pagecount is the sum of convertedpages and changedpages. I need to select all rows along with pagecount and i cant group them. I am wondering if there is any way to do it? This select is part of view. so can i...
``` SELECT *, (ConvertedPages + ChangedPages) as PageCount FROM Table ```
If I'm understanding your question correctly, while I'm not sure why you can't use `group by`, another option would be to use a `correlated subquery`: ``` select distinct id, (select sum(field) from yourtable y2 where y.id = y2.id) summedresult from yourtable y ``` --- This assumes you have data such as: ``...
How to sum two columns in sql without group by
[ "", "sql", "sql-server", "" ]
We have a script for update of a specific column. In this script we are using a `FOR UPDATE`cursor. In the first version of the script we did not use the `OF`part of the `FOR UPDATE`clause. As we found [here](https://stackoverflow.com/questions/16081582/difference-between-for-update-of-and-for-update) and [here](http:/...
According to the Oracle 11G PL/SQL documentation [here](https://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS602): > When SELECT FOR UPDATE queries multiple tables, it locks only rows > whose columns appear in the FOR UPDATE clause. So it might appear that in your example, no rows are locked and `cu...
"Can anyone explain why the script does not work without the OFclause?" You are almost there :) What does the FOR UPDATE in regular? --> locks the result set ``` SELECT t1.* FROM table_1 t1, table_2 t2, table_3 t3 WHERE t1.t2_id = t2.id AND t2.t3_id = t3.id ...
Oracle FOR UPDATE (OF) Cursor behaviour
[ "", "sql", "oracle", "plsql", "sql-update", "cursor", "" ]
I am trying to search for some duplicate records in a database, these duplicate were entered by an end user. As they were entered by an end user (presumably different people) the records are slightly different. The only thing I can possibly search on would be the company name, which as you may have guessed could potent...
Take a look at `SOUNDEX()` and `DIFFERENCE()`: [Using SOUNDEX and DIFFERENCE to Standardize Data in SQL Server](https://www.mssqltips.com/sqlservertip/2159/using-soundex-and-difference-to-standardize-data-in-sql-server/) > SOUNDEX converts an alphanumeric string to a four-character code that > is based on how the str...
This is not an SQL question actually. You are looking for a *rule* to apply instead, an algorithm. From your example you could work with a list of synonymes ('Company' = 'Co.', 'Limited' = 'LTD'). Then you'd replace all 'Company' with 'Co.', all 'Limited' with 'LTD', etc. You would then compare the result strings, pos...
SQL: Search for duplicate rows even though they might not be exact duplicates
[ "", "sql", "sql-server", "" ]
I'm trying to run a single SQL command which will update table 'name', where the column 'id' matches 'eg1', 'eg2' and 'eg3'. The column to be updated is 'status' and should be changed to 'new\_status' for the previously specified ids only. Unfortunately I'm new with SQL, therefore I only got as far as this which doesn...
``` Update tblhosting set status = 'new_status' where id in ('eg1','eg2','eg3') ``` This assuems you want to update tblhosting column status set to 'new\_status' where the ID is either eg1, eg2 or eg3.
String literals are enclosed in single quotes. Identifiers can be optionally enclosed in backtick characters. The syntax for an `UPDATE` statement is like this: ``` UPDATE `tblhosting` SET `status` = 'new_status' WHERE `id` IN ('eg1','eg2','eg3') ``` The specification is a little ambiguous. The example ab...
Updating column for more than one row
[ "", "mysql", "sql", "" ]
I have 4 tables in my Database **Bookings** ``` Booking_Id : int, Primary Key Hotel_No : int, foreign key Guest_No : int, foreign key Date_From : date Date_To : date Room_No : int, foreign key ``` **Guest** ``` Guest_No : int, primary key Name : varchar(30) Address : varchar(50) ``` **Hotel** ``` Hotel_No : int...
I Found the solution: ``` select Room.*, Guest.Name from Room left join(select * from Booking where Booking.Date_From <= GetDate() And Booking.Date_To >= GetDate()) as book on room.Room_No = book.Room_No left join Guest on book.Guest_No = Guest.Guest_No where Room.Hotel_No = 6 ```
try this: ``` Select r.*, g.name from Room as r left join Booking as b on r.Room_No = b.Room_No left join Guest as g on g.Guest_No = b.Guest_No left join Hotel as h on h.Hotel_No = b.Hotel_No where h.Hotel_No = 6 AND b.Date_From <= cast(GETDATE() as date) ```
SQL - Join and Subqueries
[ "", "sql", "sql-server", "database", "" ]
I have the following statement which is going to run automatically several times a month : ``` select case when to_char(sysdate, 'MM') <> '03' or (to_char(sysdate, 'MM')= '03' and count(a.cust_id) >'1000000') then '0' when to_char(sysdate, 'MM')= '03' and count(a.cust_id) <'1000000' the...
Oracle [uses short-circuit evaluation](http://docs.oracle.com/cd/E11882_01/server.112/e41084/expressions004.htm): > Oracle Database uses short-circuit evaluation. For a simple CASE expression, the database evaluates each comparison\_expr value only before comparing it to expr, rather than evaluating all comparison\_ex...
Check this script : ``` select case when to_char(sysdate, 'MM') <> '03' or (to_char(sysdate, 'MM')= '03' and count(a.cust_id) >'1000000') then '0' when to_char(sysdate, 'MM')= '03' and count(a.cust_id) <'1000000' then '1' else 'Your Text' end...
use of condition with CASE on oracle sql
[ "", "sql", "oracle", "case", "" ]
I want to search through a SQL table and find two consecutive missing dates. For example, person 1 inserts 'diary' entry on day 1 and day 2, misses day 3 and day 4, and enters an entry on day 5. I am not posting code because I am not sure of how to do this at all. Thanks!
My high level approach to this problem would be to select from a dynamic table of dates, using an integer counter to add or subtract from the current DateTime to get as many dates as you require into the future or past, then LEFT join your data table to this, order by date and select the first row, or N many rows which...
This uses a LEVEL aggregate to build the list of calendar dates from the first entry to the last, then uses LAG() to check a given date with the previous date, and then checks that neither of those dates had an associated entry to find those two-day gaps: ``` With diary as ( select to_date('01/01/2016','dd/mm/yyyy...
Searching SQL table for two consecutive missing dates
[ "", "sql", "oracle", "search", "" ]
I'm going through a SQL tutorial, and came across this question. I've been stuck for sometime. **Customers** ``` id INTEGER PRIMARY KEY lastname VARCHAR firstname VARCHAR ``` **Purchases** ``` id INTEGER PRIMARY KEY customers_id INTEGER FOREIGN KEY customers(id) purchasedate DATETIME purchaseamo...
Yeah, or to avoid the whole `distinct` business you could write ``` SELECT id, LastName, firstname FROM Customers WHERE EXISTS ( SELECT 1 FROM Purchases WHERE customers_id=Customers.id AND MONTH(purchasedate)=2 AND YEAR(purchasedate)=2016 ) ```
I will go with `EXISTS` which will avoid duplicate ``` SELECT Customers.id, Customers.LastName, Customers.firstname FROM Customers WHERE EXISTS (SELECT 1 FROM Purchases WHERE Purchases.customers_id = Customers.id AND Month(purchasedate) = 2) ``` ...
SQL Query for all purchases in a given month
[ "", "sql", "" ]
I'm currently working on a query that should return a *subset* of a CartoDB table (i.e. a new table) sorted by proximity to a given point. I want to display labels on the map corresponding to the closest, second closest, etc. and thought to capture that by using the PostgreSQL row\_number() method in a new column: ```...
You **CANT** use a field calculated on the same level. ``` SELECT (x1-x2)^2 + (y1-x2)^2 as dist, dist * 1.6 as miles ^^^^^ undefined ``` So you create a subquery. ``` SELECT dist * 1.6 as miles FROM ( SELECT (x1-x2)^2 + (y1-x2)^2 as dist ...
You cannot use a column alias in another column. Here you are defining `dist` for result list and also use it in the `row_number`'s `ORDER BY`. You have to write the same expression that you used for `order` instead.
PostgreSQL "column does not exist" error in CartoDB
[ "", "sql", "postgresql", "postgis", "cartodb", "" ]
I have a column which contains many records with one word in common (e.g Channel names): ``` | channel | -------------------------- | Fox | | Fox Life | | Fox News | | Fox Action | | Fox Movies | ``` And the search criteria is: "Channel F...
This screams for fulltext index ``` ALTER TABLE T add FULLTEXT index(channel); ``` You search with ``` SELECT * FROM t WHERE MATCH (channel) AGAINST ('+Fox +News' IN BOOLEAN MODE); ``` plus sign means that word HAS to exist in the column There are a couple of things you need to pay attention to: [innodb\_ft\_m...
How about using `like`? ``` where lower(channel) like '%fox news%' ```
Select records with spaces in mysql
[ "", "mysql", "sql", "" ]
I have to select a bunch of rows from a database (DB2), based on an array of ID's. However as the amount of rows can become rather large (up to 7,000), the multi-row query (below) will fall to the 30 seconds time-out in VBA. I am instead considering a looped single-row approach, but I have no clue how much stress this ...
7000 calls will be very slow, because of the number of round-trips. The best approach to solving this problem is creating a temporary table, populating it with 7000 rows, and joining to it in your query. If this approach is not acceptable, you could limit the number of round-trips by querying, say, a 1000 rows at a t...
The looped single-row query is more reckless. Well, at least it doesn't perform as well. In general, executing a query incurs overhead. At the very minimum, the databases engine needs to parse the query, determine the query plan (which may be passed), execute the query, and return the results. Repeating this steps req...
Multiple queries vs. huge WHERE IN
[ "", "sql", "vba", "db2", "" ]
I have Ip2LocationLite database with ip\_from, ip\_to, country\_code columns. All IP's are in decimal format (converted using a function). So I have to detect those users with IP addresses from certain country. For example, Russia has over 3 thousands IP ranges and I want to search through all of them. Script looks ...
It can be a little tricky to answer these questions without a few sample records and the expected output. But if I've understood your schema correctly you can use a join instead of the sub queries. **Example** ``` SELECT * FROM [dbo].[USERINFO] as UserInfo INNER JOIN [ip2location].[dbo].[ip2locatio...
Get the `min/lowest` value from your first sub-query and the `max/highest` value from your second sub-query to avoid the error and if you want to use them as parameters for your `BETWEEN` clause. If your IP addresses are canonical or can be ordered numerically, you may get the lowest IP value by sorting them in ASC or...
How to make multiple BETWEEN statements not knowing the quantity of them beforehand? (detecting country by IP range)
[ "", "sql", "sql-server", "geolocation", "ip", "between", "" ]
I need to show serial numbers for each row of an invoice. That means, that on one position there can be several serial numbers. Along with the serial number there needs to be a quantity, which is obviously allways one. Unfortunately, there could be rows with more items than serial numbers. This happens when serial numb...
``` select s.doc, s.pos, s.serial, d.qty - s.cnt qty from ( select s.doc, s.pos, s.serial, count(*) cnt, case when grouping(s.doc) = 0 and grouping(s.pos) = 0 and grouping(s.serial) = 1 then 1 else 0 end grp from #serial s group by s.doc, s.pos, s.serial with cube having grouping(s.doc) =...
Dynamic approach ``` SELECT d.doc, d.pos, s.serial, 1 qty FROM #data d INNER JOIN #serial s ON s.doc = d.doc and s.pos = d.pos UNION select t1.doc,t1.pos,null,t1.qty-ss from ( SELECT d.doc,d.pos, SUM(1) SS , d.qty FROM #data d INNER JOIN #serial s ON s.doc = d.doc and s.pos...
Add summarizing column with calculation
[ "", "sql", "sql-server", "summarization", "" ]
I have created a table ``` CREATE TABLE `region_details` ( `id` int(5) NOT NULL, `file_id` varchar(20) NOT NULL, `region` varchar(30) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ``` Lets assume I have 10 records as follows ``` id file_id region 1 aaa a 2 bbb ...
Simply do a `GROUP BY`, use `MIN(id)` to pick each region's first id. ``` select min(id) as id, region from region_details group by region ```
You can do it like this: ``` SELECT min(id),region FROM YourTable GROUP BY region ```
How to select only distinct values for two columns in mysql
[ "", "mysql", "sql", "" ]
This is my SQL clause ``` ISNULL((LTRIM(RTRIM(Masters.comment1))+';'+LTRIM(RTRIM(masters.comment2))),'')Note1 , ``` When there are no value in both the column, then I am getting only a semicolon. If the value is not in `comment1` then I am getting `;xyz`. I want that: * when no value is in `comment1` and `comment2`...
This will add the semicolon when there is data is both columns ``` SELECT COALESCE(LTRIM(RTRIM(comment1)),'') + CASE WHEN NULLIF(comment1, '') + NULLIF(comment2, '')IS NULL THEN '' ELSE ';' END + COALESCE(LTRIM(RTRIM(comment2)),'') FROM yourtable ```
You can use `NULLIF` to turn empty string to `NULL`. Then concatenation of `NULL` with ';' would still be `NULL` and that can be turned into and empty string with `ISNULL`: ``` WITH masters (comment1, comment2) AS ( SELECT NULL, NULL UNION ALL SELECT ' 1', NULL UNION ALL SELECT NULL, '2 ' UNION ALL SEL...
Inserting an optional semicolon between two selected fields
[ "", "sql", "sql-server", "t-sql", "" ]
I want to find only records that exist in one table, that don't exist in another table. The part I'm struggling with is that one item can have multiple variations. Example Table one ``` ItemNumber | VendorName 1 | Frito Lay 1 | Joe's Chips 1 | Chips Galore ``` Example Table...
``` SELECT ItemNumber, VendorName from Table1 except select ItemNumber, VendorName from Table2 ``` This will select everything in the "first" set that is not also found in the "second" set... and it checks every specified column in every row column in doing it. (Duplicates are removed.)
You can use `NOT EXISTS`: ``` SELECT * FROM dbo.TableOne T1 WHERE NOT EXISTS(SELECT 1 FROM dbo.TableTwo WHERE ItemNumber = T1.ItemNumber AND VendorName = T1.VendorName); ``` Another option could be using `EXCEPT`: ``` SELECT * FROM dbo.TableOne EXCEPT SELECT * FROM dbo.TableTwo; ``...
How to find records that exist in one table but not the other when each record has variations
[ "", "sql", "sql-server-2008", "" ]
Here is my database structure, it contains 3 tables : School, Student, Course Each student must belong to a school (so School ID will be a foreign key in the student table referring to the School table). Each course also must belong to a school (so School ID will be a foreign key in the course table referring to the ...
You can add the SchoolID as a part Primary keys in both Student and Course. This will force foreign keys to those tables to also specify the SchoolID. We use this fact in our StudentInCourse-table to force both the student and the course to belong to the same school. ``` CREATE TABLE School(id INT PRIMARY KEY); CRE...
I recommend to make : - The three fields Pivot`(StudentID,CourseID,SchoolID)` a `Primary Key`- The two fields Pivot`(StudentID,SchoolID)` a double `Foreign Key` to the `Student` table- The two fields Pivot`(CourseID,SchoolID)` a double `Foreign Key` to the `Course` table So the model will be in this way: School Tabl...
SQL db design constraints for co-belonging
[ "", "sql", "database", "constraints", "foreign-key-relationship", "" ]
I have a dataset like the one below, and I would like to remove the date component from it. One challenge is that the date can be in different formats as shown below. **Existing output** ``` Event A 05-25-2015 Event B 25-05-2015 Event C April 2015 Event D 2016 ``` **Desired Output** ``` Event A Event B Event C Even...
Something to get you started. Depending on the number of formats that you might face, you might want to put them all into a table as patterns, join to that table, and use `LEN` to calculate values for the `STUFF` command. ``` DECLARE @test TABLE (my_string VARCHAR(50) NOT NULL) INSERT INTO @test (my_string) VALUES ...
Here another way using `CROSS APPLY` should handle any format of data. This will consider than you have **two space** in your data and extracts the data which is before the second space. ``` CREATE TABLE #strings ( col VARCHAR(50) ) INSERT INTO #strings VALUES ('Event A 05-25-2015'), ('Even...
Remove date from text in SQL
[ "", "sql", "sql-server", "date", "" ]
We're supposed to make a function that adds +7 days to the current `SYSDATE`, and also write the time and minute, however, my code only displays the date, not the time. What am I doing wrong? This is probably very easy, but I just can't figure it out, and there's not much help on the Internet either. So far, I've trie...
You have to format the result to your specifications, as in ``` --create the function CREATE OR REPLACE FUNCTION get_date(n IN NUMBER) RETURN DATE AS BEGIN RETURN SYSDATE + n; END get_date; --call the function SELECT TO_CHAR(get_date(7), 'DD.MM.YYYY HH24:MI') FROM dual; ``` Or your new requirement of no formatt...
You can decide if you want your function to return a `date` or a `varchar`; you may choose one of the following ways, depending on your need: ``` CREATE OR REPLACE FUNCTION get_date(n IN NUMBER) RETURN varchar2 AS BEGIN RETURN to_char(SYSDATE + n, 'DD.MM.YYYY HH24:MI'); END get_date; / CREATE OR REPLACE FUNCTION ...
PL/SQL function to add +7 days to SYSDATE
[ "", "sql", "oracle", "function", "sysdate", "" ]
I try to create in SSRS a chart which should show me only the Sunday at 10 pm until 11 pm value. My query: ``` select intervaldateweek as Week, SUM(GoodUnits) As GoodUnits, SUM(NetUnits) As NetUnits, SUM(GoodUnits) / NULLIF(SUM(NetUnits) , 0.0)* 100 As Value from Count inner join tsystem ON ...
You can use the `DATEPART` function ([documentation here](https://msdn.microsoft.com/en-us/library/ms174420.aspx)) to look at the relevant parts, like the hour of a date time value. For example: ``` SELECT intervaldateweek AS [Week], SUM(GoodUnits) AS GoodUnits, SUM(NetUnits) AS NetUnits, SUM(GoodUnit...
try this ``` select intervaldateweek as Week, SUM(GoodUnits) As GoodUnits, SUM(NetUnits) As NetUnits, SUM(GoodUnits) / NULLIF(SUM(NetUnits) , 0.0)* 100 As Value from Count inner join tsystem ON Count.systemid = tsystem.ID where DATEPART(dw,intervaldate) = 1 AND CAST(intervaldate AS TIME(0)) BETWEEN CAST('22...
Determine a time interval
[ "", "sql", "sql-server", "reporting-services", "ssrs-2008-r2", "" ]
Hi I need to merge 2 tables with information about customers. Table 2 tells us if we have customer information about email, address and phonenumber, but the data is structured so each customer has 3 rows. Is there a way to merge these two tables so that I only get one row per customer but with all the contact informati...
You can replace those three joins with a single usong conditional aggregation (=pivot): ``` TABLE1 left join( select customerID, max(case when Y_N='Y' and Channel='Email' then 1 else 0 end) as Email max(case when Y_N='Y' and Channel='Address' then 1 else 0 end) as Address max(case when Y_N='Y...
Well, if it works, why change it? But if you have to, maybe something like: ``` SELECT c.*, IF(e.Y_N='Y',1,0) AS Email, IF(a.Y_N='Y',1,0) AS Address, IF(p.Y_N='Y',1,0) AS Phone FROM table1 AS c LEFT JOIN table2 AS e ON(c.customerID=e.customerID AND Channel='Email') LEFT JOIN table2 AS a ON(c.cust...
Several rows with info to a single row
[ "", "sql", "teradata", "" ]
SQL MINUS is used as: ``` SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions] MINUS SELECT expression1, expression2, ... expression_n FROM tables [WHERE conditions]; ``` In case I see no difference between first minus second but see a difference between second minus first, what does this ...
If I understand you correctly, there are two cases of the problem as follows: 1. Table1 and Table2 have ame number of rows, but different values: In this case using Table1 Minus Table2 will have the same results as Table2 Minuse table1. 2. Different number of rows: In this case, Table1 Minus Table2 will only return th...
You can refer the docs to understand the [MINUS operator](http://www.techonthenet.com/sql/minus.php): > The Oracle MINUS operator is used to return all rows in the first > SELECT statement that are not returned by the second SELECT statement. > Each SELECT statement will define a dataset. The MINUS operator will > ret...
SQL MINUS showing no difference between first and second while shows difference between second and first
[ "", "sql", "oracle", "oracle11g", "" ]
I need to see only the current year rows from a table. Would it be possible filter a timestamp column only by current year parameter, is there some function that can return this value? ``` SELECT * FROM mytable WHERE "MYDATE" LIKE CURRENT_YEAR ```
In PostgreSQL you can use this: ``` SELECT * FROM mytable WHERE date_part('year', mydate) = date_part('year', CURRENT_DATE); ``` The date\_part function is available in all PostgreSQL releases from current down to 7.1 (at least).
This is pretty old, but now you can do: ``` SELECT date_part('year', now()); -> 2020 ``` In the place of `now` you can pass any timestamp. More on [Documentation](https://www.postgresql.org/docs/8.2/functions-datetime.html)
Postgresql query current year
[ "", "sql", "postgresql", "" ]
Consider this data: ``` ---+-----------+-------+--+ | id | name | grade | | +----+-----------+-------+--+ | 13 | Maria | 10 | | | 18 | Lorenzo | 10 | | | 2 | Cissa | 10 | | | 3 | Neto | 9 | | | 15 | Gabriel | 9 | | | 10 | Laura | 9 | | | 12 | Joãozinho | 8 | ...
You can do this using a `join`: ``` select s.* from student s join (select grade from student group by grade order by grade desc limit 3 ) g3 on s.grade = g3.grade; ``` In most databases, you an do this using `in`: ``` select s.* from student s where s.grade in (select grade ...
``` select s1.* from students s1 join (select distinct grade from students order by grade desc limit 3) s2 on s1.grade = s2.grade ``` Alternatively: ``` select * from students where grade >= (select distinct grade from students order by grade desc limit 2,1) ```
Select groups with the three biggest values
[ "", "mysql", "sql", "select", "group-by", "limit", "" ]
So this is table A ``` +------------+--------+----------+ | LineNumber | Pallet | Location | +------------+--------+----------+ | 1 | a | X | +------------+--------+----------+ | 2 | a | X | +------------+--------+----------+ | 3 | b | Y ...
my dummy data are same as @Backs. Also i think it should partition on Location. I have use exists clause instead of inner join. ``` ;WITH Cte AS ( SELECT LineNumber ,Pallet ,Location ,ROW_NUMBER() OVER ( PARTITION BY t.Location ORDER BY t.LineNumber ) AS RowId ...
``` DECLARE @Test1 TABLE ( LineNumber int, Pallet nvarchar(10), Location nvarchar(10) ) DECLARE @Tsst2 TABLE ( MaxPalCount int, Location nvarchar(10) ) INSERT INTO @Test1 (LineNumber,Pallet,Location) VALUES (1, 'a', 'X'), (2, 'a', 'X'), (3, 'b', 'Y'), (4, 'b', 'Y'), (5, 'b', 'Y'), (6, 'c', 'Z'), (...
How to query only rows that will exceed to the max quantity
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I have a table with duplicates like that: ``` ClassId Name Days SpecHours 1 Jack 250 130 1 Jack 250 130 1 Jack 250 120 2 Mike 300 130 … ``` What I want is to sum totalSpecHours for non-duplicates. My expected output is: ``` ClassId Name Days totalSpe...
Try this query: ``` select classID, Name, Days, sum(specHours) as TotalSpecHours from ( select distinct ClassId, Name, Days, SpecHours from myTable )t group by classID, Name, Days ``` **Logic:** We take distinct values in inner query and then over this result set we do a group by and get the sum. Pleas...
Shouldn't something like this work? ``` SELECT ClassId, Name, Days, SUM(SpecHours) AS totalSpecHours FROM ( SELECT DISTINCT ClassId, Name, Days, SpecHours FROM Table ) outer GROUP BY ClassId, Name, Days ```
Summing a column value in a table including duplicates
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I tried the following example in Oracle 11g: <http://joshualande.com/filters-joins-aggregations/> ``` SELECT c.recipe_name, COUNT(a.ingredient_id), SUM(a.amount*b.ingredient_price) FROM recipe_ingredients a JOIN ingredients b ON a.ingredient_id = b.ingredient_id JOIN recipes c ON a.recipe_id = c.recipe_id GROUP BY a...
In the SELECT clause, you can only refer to expression that either appear in the GROUP BY clause or are aggregations (such as SUM). `c.recipe_name` does not qualify as such. You might know that grouping by `a.recipe_id` will lead to a unique result for `c.recipe_name` (within each group). And Oracle might even be able...
You have to also put field `c.recipe_name` in the `GROUP BY` clause: ``` SELECT c.recipe_name, COUNT(a.ingredient_id) AS cnt, SUM(a.amount*b.ingredient_price) AS sum FROM recipe_ingredients a JOIN ingredients b ON a.ingredient_id = b.ingredient_id JOIN recipes c ON a.recipe_id = c.recipe_id GROUP B...
ORA-00979: not a GROUP BY expression with a simple example
[ "", "sql", "oracle", "oracle11g", "group-by", "ora-00979", "" ]
I have sequences like table\_name\_sq in postgresql for all tables. For example; ``` seqtest-> seqtest_sq seqtest2-> seqtest2_sq ``` I need to change all sequences in database. (I cannot run query for every tables manually) I can get tables and make sequence string ``` select table_name || '_sq' as sequence_name fr...
Here is the solution with help of @Nick Barnes and @a\_horse\_with\_no\_name If someone needs a idea of how to fix sequences can use this script. ``` DO $$ DECLARE i TEXT; BEGIN FOR i IN (select table_name from information_schema.tables where table_catalog='YOUR_DATABASE_NAME' and table_schema='public') LOOP ...
Here is the script I use. ``` DO $$ DECLARE i TEXT; BEGIN FOR i IN ( SELECT 'SELECT SETVAL(' || quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname)) || ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM ' || quote_ident(PGT.schemaname)|| '.'||quote_ident(T.r...
postgresql change all sequences with for loop
[ "", "sql", "postgresql", "for-loop", "" ]
I'm writiting a store procedure. This procedure is getting 4 arguments which will be used in `where` clause. Problem is that these parameters can be empty. I'm trying to write something like this: ``` select * from Books If(@param1 <> "") add where title =@param1 to the clause ``` But I have no idea how to make it...
This type of query is called [catch-all-query](http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/). There are several ways to do this, one of which is using combinations of`AND` and `OR` conditions: ``` SELECT * FROM Books WHERE (@param1 = '' OR title = @param1) ``` Another way is to u...
You can try like this ``` Select * from Books where (Title=@title or @title='') ```
Conditionally add where to the statement
[ "", "sql", "sql-server", "" ]
I'm having a table with an id and a name. I'm getting a list of id's and i need their names. In my knowledge i have two options. Create a forloop in my code which executes: ``` SELECT name from table where id=x ``` where x is always a number. or I'm write a single query like this: ``` SELECT name from table where...
SQLite has [limits](http://www.sqlite.org/c3ref/limit.html) on the size of a query, so if there is no known upper limit on the number of IDs, you cannot use a single query. When you are reading multiple rows (note: `IN (1, 2, 3)` is easier than many ORs), you don't know to which ID a name belongs unless you also SELEC...
A "nice" solution is using the `IN`operator: ``` SELECT name from table where id in (1,2,3) ```
SQL or statement vs multiple select queries
[ "", "sql", "sqlite", "" ]
This is my query: ``` SELECT d.DeptName, CASE WHEN e.WorkCity is NULL THEN 'Mobile' ELSE 'Stationary' END AS EmpType, AVG(e.MonthlyPayScale) AS AvgMnthPay FROM Department d, Employee e WHERE d.DeptId = e.DeptId GROUP BY d.DeptName, EmpType ORDE...
The processing that you describe is often used to explain the *compilation* of a query and what identifiers are known when. SQL Server is very explicit about this, and their rules are documented [here](https://msdn.microsoft.com/en-us/library/ms189499.aspx). Just because SQL Server does it that way, does not mean that...
Do the `CASE` expression in a derived table: ``` select DeptName, EmpType, AVG(MonthlyPayScale) AS AvgMnthPay FROM ( SELECT d.DeptName as DeptName, CASE WHEN e.WorkCity is NULL THEN 'Mobile' ELSE 'Stationary' END AS EmpType, e.MonthlyPayScale as MonthlyPayScale FROM Departm...
Using SELECT'd Case Statement's columnName in GROUP BY
[ "", "sql", "postgresql", "" ]
I'm working on a system to manage students attendance in class. I created two tables: student (student\_id,name,mail..) and course (course\_id, name, lecturer...). now my question is how should i keep record of which students taking which courses? should i create another table for each course with this structure: cour...
Since there is a many to many relations between your tables(every student can take many courses,each course can be taken by multiple students) you need an intermediary table which hold the primary key of both table. ``` coursestudent(course_id,student_id) ``` with FOREIGN KEYs to the respective tables.
Depends, if a student can have multiple courses and a course belongs to multilple students you want to make a table that contains id, course\_id(FOREIGN KEY) and student\_id(FOREIGN KEY). If a student can have only one course, but a course can be followed by multiple students you probably want to add course\_id to stu...
good practice in MySQL DB structure
[ "", "mysql", "sql", "" ]
I'm using Apache Derby 10.10. I have a list of participants and would like to calculate their rank in their country, like this: ``` | Country | Participant | Points | country_rank | |----------------|---------------------|--------|--------------| | Australia | Bridget Ciriac | 1 | ...
**SQL** ``` SELECT c.name AS Country, p.name AS Participant, p.points AS Points, (SELECT COUNT(*) FROM Participant p2 JOIN Team t2 ON p2.team_id = t2.id WHERE t2.country_id = t.country_id AND (p2.points < p.points OR p2.points = p.points AND p2.name...
Consider a non-windows function SQL query that uses a correlated aggregate count subquery. Because the group column (`Country.name`) is not in same table as the rank criteria (`Participant.points`), we need to run same joins in the subquery but rename table aliases to properly compare inner and outer queries. Now of c...
Query to rank rows in groups
[ "", "sql", "derby", "rank", "row-number", "groupwise-maximum", "" ]
When I try to run this query: ``` select branch_no, max (avg_salary) from (select allocatedto, avg (salary) from staff, worker where staff.staff_no = worker.staff_no group by allocatedto) as branch_avg (branch_no, avg_salary); ``` I get this error: ``` Error: near "(": syntax error ```
``` select my_alias1,my_alias2 from (select col1,col2,...) as A (my_alias1,my_alias2) ``` The above syntax is valid in `SQL Server`. To alias the column in derived table you need to use `AS` inside the derived table. Try this ``` SELECT Max (avg_salary) FROM (SELECT allocatedto AS branch_no, Avg (s...
In SQLite, an AS clause on a subquery cannot assign column names (and it is not needed in the first place). To rename the output columns of a (sub)query, you must use AS in the SELECT clause: ``` SELECT branch_no, max(avg_salary) AS avg_salary FROM (...); ```
SQL syntax error: near "("
[ "", "sql", "sqlite", "subquery", "derived-table", "" ]
I'd like to find a way to drop multiple indexes from various tables with a single query in SQL Server. I can find the index name and table by using the query below, but I'm a bit lost on how I should go about dropping the tables it finds. ``` SELECT so.name AS TableName , si.name AS IndexName ...
You can construct your drop script starting from your `SELECT`: ``` DECLARE @SQL NVARCHAR(MAX) = N'' SELECT @SQL = @SQL + 'DROP INDEX ' + so.name + '.' + si.name + ';' + CHAR(13) + CHAR(10) FROM sys.indexes si JOIN sys.objects so ON si.[object_id] = so.[object_id] WHERE so.type = '...
This is one of those times in life you generally will want to use a cursor, because your statement is dynamic. ``` DECLARE drop_cur cursor for SELECT QUOTENAME(so.name) AS TableName, QUOTENAME(si.name) AS IndexName, si.type_desc AS IndexType FROM sys.indexes si ...
Drop index if name like
[ "", "sql", "sql-server", "" ]
I have the following table ``` Date Value promo item 01/01/2011 626 0 1230 01/02/2011 231 1 1230 01/03/2011 572 1 1230 01/04/2011 775 1 1230 01/05/2011 660 1 1230 01/06/2011 662 1 1230 01/07/2011 541 1 1230 01/08/2011 849 1 1230 01/09/2011 632 1 1230 01/10/2011 906 1 1230 01/11/201...
Here is an alternate approach that requires LAG() which is available from SQL 2012, but note the sample data does not contain "28 distinct days" prior to each date. Also the actual data type being used isn't known (date/smalldatetime/datetime/datetime2) nor is it known if truncating time from date is needed. So with so...
if you are looking for cumulative sum for all days excluding first 12 days from mindate... ``` with cte as ( select dateadd(day,12,min(date)) as mindate,max(date) as maxdate, datediff(day,dateadd(day,12,min(date)),max(date)) as n from #RollingTotalsExample ) select date, (select sum(value) from #RollingTotalsExample...
Custom calculation for amount
[ "", "sql", "sql-server", "sql-server-2008", "" ]
[![enter image description here](https://i.stack.imgur.com/CBhQp.png)](https://i.stack.imgur.com/CBhQp.png) This is my table. I need to write a query that shows all the records but when a project reaches 100% It shows the record for that project only once. so the result should be [![enter image description here](https...
Use `NOT EXISTS` to return a row if no other row for the same project already (lower date) has reached 100%: ``` SELECT t1.* FROM table_name t1 WHERE NOT EXISTS (select 1 from tablename t2 where t2.project = t1.project and t2.report_date < t1.report_date and t2...
You could use `GROUP BY`: ``` SELECT project, MIN(report_date) AS report_date, percentage FROM table_name GROUP BY project, percentage ORDER BY project, report_date; ``` `MIN` will select first date when percentage is the same. `LiveDemo` Output: ``` ╔═════════╦═════════════════════╦════════════╗ ║ project ║ r...
sql how to show row with same column value only once
[ "", "sql", "" ]
I have 2 sprocs for an assignment, what I'm trying to do is pass the xml output from one sproc to another and put it in a variable, I know ex1.xml\_sp1 is returning an int while calling it with `EXEC` and obviously when trying to select this it returns null because `@x` is xml data type. What I want to do is retrieve ...
> I want to do is retrieve and store the xml data from sproc 1 in to @x in sproc 2. You could achieve it very easily using [`OUTPUT` parameters](https://msdn.microsoft.com/en-us/library/ms378108%28v=sql.110%29.aspx): ``` CREATE PROCEDURE [xml_sp1] @careteamid INT, @xml_output XML OUTPUT AS BEGIN SET @xml_out...
For the return value (i.e. `EXEC @ReturnValue = StoredProcName...;`), `INT` is the only datatype allowed. If this needs to really stay as a Stored Procedure then you can either use an `OUTPUT` variable or create a temp table or table variable in the second Stored Procedure and do `INSERT INTO ... EXEC StoredProc1;`. H...
How can I pass xml data from one sproc to another?
[ "", "sql", "sql-server", "xml", "sql-server-2008", "t-sql", "" ]
In a DB I have a table `tca` with a `status` column. This can be `new, process, completed`, etc.When I query this table with `SELECT status, count(*) FROM tca GROUP BY status` to find out the count of a certain status I get follwing multidimensional array back ``` Array ( [0] => Array ( [status...
Since you have selected 'status' and 'count(\*)' , these keys are present in your result array. Also same result is there with numeric index of result array.
Hope this solve your query. ``` Use mysqli_fetch_assoc($dbcon,$countQuery); //$dbcon = your db connection variable // $countQuery = your query ```
mySQL count(*) meaning of arrays
[ "", "mysql", "sql", "" ]
There are 2 tables, a Component table and a Log table. The component table holds the actual(current) value description and a timestamp when it was last updated. The Log table contains a component ID that references to wich component it belongs: ``` Component: Id Actual LastUpdated Log: Id ComponentId Value Timesta...
I think you're going about this all wrong. A better solution would be a trigger on the Component table, that inserts into the Log table whenever a Component is inserted or updated. ``` CREATE TRIGGER trg_component_biu ON Component AFTER INSERT, UPDATE AS BEGIN INSERT INTO Log( ComponentId, Value, ...
All data in your Component table is coming from the Log table. Instead of making Component an actual table, you can make it a view, indexed if necessary. ``` CREATE VIEW Component WITH SCHEMABINDING AS SELECT ComponentId AS Id, FIRST_VALUE(Value) OVER(PARTITION BY ComponentId ORDE...
Looking for an alternative method to this query
[ "", "sql", "sql-server", "" ]
I need to select all free rooms from `hotel` DB and I think I can do it with two steps: 1. `bookings = select * from booking where booking.startDate>=selectedStartDate and booking.endDate=<selectedEndDate`. 2. pseudo query: `select * from room where room.room_id not includes bookings.room_id`. I wrote my second query...
You could transform the first query to a subquery of the second query by using the `not in` operator: ``` SELECT * FROM room WHERE room.room_id NOT IN (SELECT room_id FROM booking WHERE startDate >= selectedEndDate AND end...
If you want rooms free during a period of time, use `not exists`. The correct logic is: ``` select r.* from room r where not exists (select 1 from booking b where $startdate <= b.enddate and $enddate >= b.startdate ); ``` Two periods overlap when one starts before ...
SQL query to check if column includes some data
[ "", "mysql", "sql", "database", "select", "" ]
I have a complex query which requires fields from a total of 4 tables. The inner joins are causing the query to take much longer than it should. I have run an EXPLAIN statement, whose visual result is attached below: [![EXPLAIN Statement output](https://i.stack.imgur.com/RJ8Ze.png)](https://i.stack.imgur.com/RJ8Ze.png...
Rewriting as a `UNION` is simple, copy the source and remove one of the `OR`ed conditions in each: ``` SELECT pending_corrections.corrected_plate , pending_corrections.seenDate FROM (pending_corrections INNER JOIN cameras ON pending_corrections.camerauid = cameras.camera_id) INNER JOIN vehicle_...
you may try the following: ``` select pending_corrections.corrected_plate , pending_corrections.seenDate from pending_corrections where pending_corrections.seenDate >= '2015-01-01 00:00:00' and pending_corrections.seenDate <= '2015-01-31 23:59:59' and exists(select 1 from cameras where pending_corrections.came...
How to handle multiple joins
[ "", "mysql", "sql", "database", "performance", "relational-database", "" ]
I want to get all the possible `type` from a table and then `count` the rows under a `group` who has this `type`. To better illustrate consider the following table. ### Object (o) ``` id name group_id type ----------------------------------------------------------- 1 Computer 1...
You can use the following query: ``` SELECT 100 AS group_id, o.type, COUNT(CASE WHEN o.group_id = 100 THEN 1 END) AS total FROM object o GROUP BY o.type ``` This query groups by `type` and uses *conditional aggregation* so as to count the rows under each group who have `type = 100`.
The problem is that Type D is not returned in the query for that ID, so it is not included in the groupings. To do this, we need to get the list of ALL Types in the table, then do the counts for your ID in the table. Something like this: ``` SELECT o_list.type, COUNT(o.id) AS total FROM object o RIGHT OUTER JOIN ( ...
SQL Complex Counting
[ "", "sql", "oracle", "count", "group-by", "" ]
I have 2 tables - TC and T, with columns specified below. TC maps to T on column T\_ID. ``` TC ---- T_ID, TC_ID T ----- T_ID, V_ID, Datetime, Count ``` My current result set is: ``` V_ID TC_ID Datetime Count ----|-----|------------|--------| 2 | 1 | 2013-09-26 | 450600 | 2 | 1 | 2013-12-09 | 14700 ...
One method uses `row_number()`: ``` select v_id, tc_id, datetime, count from (select T.V_ID, TC.TC_ID, T.Datetime, T.Count, row_number() over (partition by t.V_ID, tc.tc_id order by datetime desc, count desc ) as seqnum from t join ...
It is possible to solve this using CTEs. First, extracting the data from your query. Second, get the maxdates. Third, get the highest count for each maxdate.: ``` ;WITH Dataset AS ( select T.V_ID, TC.TC_ID, T.[Datetime], T.[Count] from T inner join TC on TC.T_ID = T._ID ), MaxDates AS...
SQL Server - Select Distinct of two columns, where the distinct column selected has a maximum value based on two other columns
[ "", "sql", "sql-server", "distinct", "multiple-columns", "" ]
I have a table which contains geometry lines (ways).There are lines that have a unique geometry (not repeating) and lines which have the same geometry (2,3,4 and more). I want to list only unique ones. If there are, for example, 2 lines with the same geometry I want to drop them. I tried DISTINCT but it also shows the ...
You first calculate the rows you want, and then search for the rest of the fields. So the aggregation doesnt cause you problems. ``` WITH singleRow as ( select count(way), way from planet_osm_line group by way having count(way) = 1 ) SELECT P.* FROM planet_osm_line P JOIN singleRow S ON P.way = S.way `...
To expound on @Nithila answer: ``` select count(way), way from your_table group by way having count(way) = 1; ```
SQL list only unique / distinct values
[ "", "sql", "postgresql", "postgis", "" ]
Is there a way to use `MIN` within the `WHERE` clause? I'm trying to insert a subquery into one of my scripts and the subquery I set up was originally its own query that used something like this: ``` SELECT person, MIN(date) FROM orders WHERE date > "1/1/2015" and date < "1/31/2015" GROUP BY person ``` T...
You don't need only one ``` WHERE (otherPersons, date) IN ( SELECT person, MIN(date) FROM orders WHERE date > "1/1/2015" and date < "1/31/2015" GROUP BY person ) GROUP BY person ``` This is the same as a join with two clauses ``` JOIN (...
try this code ``` SELECT person, MIN(date) as min_date -- field alias FROM orders WHERE date > "1/1/2015" and date < "1/31/2015" HAVING Min(Date) > "xx/xx/xxxx" ``` you can field alias instead of `MIN(DATE)` in `MySQL`
using MIN within WHERE
[ "", "mysql", "sql", "" ]
We're currently working on a query for a report that returns a series of data. The customer has specified that they want to receive 5 rows total, with the data from the previous 5 days (as defined by a start date and an end date variable). For each day, they want the data from the row that's closest to 4am. I managed ...
assuming that the #tTempData only contains the previous 5 days records ``` SELECT * FROM ( SELECT *, rn = row_number() over ( partition by convert(date, recorddate) order by ABS ( datediff(minute, convert(time, recorddate) , '04:00' ) ...
You can use row\_number() like this to get the top 5 last days most closest to 04:00 ``` SELECT TOP 5 * FROM ( select t.* , ROW_NUMBER() OVER(PARTITION BY t.recorddate ORDER BY abs(datediff (minute,'04:00:00.000',cast (t.recorddate as time))) rnk from #tTempData t) WHERE rnk...
Selecting 1 row per day closest to 4am?
[ "", "sql", "sql-server", "common-table-expression", "" ]
I have the following table: ``` create table Likes(ID1 number(5), ID2 number(5)); insert into Likes values(1689, 1709); insert into Likes values(1709, 1689); insert into Likes values(1782, 1709); insert into Likes values(1911, 1247); insert into Likes values(1247, 1468); insert into Likes values(1641, 1468); insert in...
You can do it with a join: ``` SELECT t.id1,t.id2 FROM Likes t INNER JOIN Likes s ON(t.id1 = s.id2 and t.id2 = s.id1) ``` Or with EXISTS() ``` SELECT t.* FROM Likes t WHERE EXISTS(select 1 FROM Likes s WHERE t.id1 = s.id2 AND t.id2 = s.id1) ```
You need to pick a given record id1=X, id2=Y only in a case when another record exists in the table, which has id1=Y, id2=X. A condition like this can be expressed in SQL with the help of EXISTS operator and a dependent subquery: ``` SELECT * FROM likes t WHERE EXISTS ( SELECT 1 FROM likes t1 WHERE t.id1 =...
How to list multiple field matches from a single table in oracle SQL
[ "", "sql", "oracle", "oracle11g", "" ]
I have a simple query as the following: ``` Select SUBSTRING(Email, Charindex('@', Email) + 1, Len(Email) - CharIndex('@', Email)) as EmailDomain, Count(Email) as Total from tblPerson Group by SUBSTRING(Email, Charindex('@', Email) + 1, Len(Email) - CharIndex('@', Email)) ``` Which is working fine except that...
The answer is simple you can not use column alias in WHERE clause or GROUP BY clause. You can try like this: ``` SELECT EmailDomain, Total FROM ( Select SUBSTRING(Email, Charindex('@', Email) + 1, Len(Email) - CharIndex('@', Email)) as EmailDomain, Count(Email) as Total from tb...
You cannot use the alias in the `GROUP BY`. To fix this, you can use a subquery: ``` SELECT t.EmailDomain, COUNT(t.Email) AS Total FROM ( SELECT SUBSTRING(Email, CHARINDEX('@', Email) + 1, LEN(Email) - CHARINDEX('@', Email)) AS EmailDomain, Email FROM tblPerson ) t GROUP BY t.EmailDomai...
SQL Server, Duplicate subquery, and Alias
[ "", "sql", "sql-server", "" ]
I'd like to use postgresql window functions like `rank()` and `dense_rank` in some queries in need to do in Django. I have it working in raw SQL but I'm not sure how to do this in the ORM. Simplified it looks like this: ``` SELECT id, user_id, score, RANK() OVER(ORDER BY score DESC) AS rank FROM g...
Since Django 2.0 it is built-in into the ORM. See [window-functions](https://docs.djangoproject.com/en/2.0/ref/models/database-functions/#window-functions) ``` # models.py class GameScore(models.Model): user_id = models.IntegerField() score = models.IntegerField() # window function usage from django.db.mode...
There are a few ways of doing this: 1) Using annotate and RawSQL(). Preferred method. Example: ``` from django.db.models.expressions import RawSQL GameScore.objects.filter().annotate(rank=RawSQL("RANK() OVER(ORDER BY score DESC)", []) ) ``` 2) Using GameScore.objects.filter(...).extra() function. As this is an old...
Clean way to use postgresql window functions in django ORM?
[ "", "sql", "django", "postgresql", "orm", "" ]
I have a table with all word positions in a book the table is like this ``` Word PageNo Position ---------------------- A 1 10 A 1 15 B 1 13 B 2 18 C 2 20 ``` I want to find the pages that has word A and word B the result is page 1 I can get th...
``` select * from tablename where PageNo in (select PageNo from tablename where Word in ('A','B') group by PageNo having count(distinct Word) >= 2) ```
Try this: ``` SELECT Word, PageNo, Position FROM t WHERE PageNo IN (SELECT PageNo FROM t WHERE word IN ('A', 'B') GROUP BY PageNo HAVING COUNT(DISTINCT word) = 2) ```
SQL query for book search
[ "", "sql", "" ]
I am using PostgreSQL version 8.1. I have a table as follows: ``` datetime | usage -----------------------+---------- 2015-12-16 02:01:45+00 | 71.615 2015-12-16 03:14:42+00 | 43.000 2015-12-16 01:51:43+00 | 25.111 2015-12-17 02:05:26+00 | 94.087 ``` I would like to add the integer values...
Below query should give you the desired result: ``` select to_char(timestamp, 'YYYY-MM-DD') as time, sum(usage) from table group by time ```
This one is for postgreSQL, I see you added MySQL also. ``` SELECT dt SUM(usage), FROM ( SELECT DATE_TRUNC('day', datetime) dt, usage FROM tableName ) t GROUP BY dt ```
Sum Column of Integers Based on Timestamp in PostgreSQL
[ "", "sql", "postgresql", "datetime", "" ]
I recently upgraded our SQL Server from 2005 to 2014 (linked server) and I am noticing that one of the stored procedures which calls the exec command to execute a stored procedure on the upgraded linked server is failing with the error > Could not find server 'server name' in sys.servers.Verify that the correct server...
I figured out the issue. The linked server was created correctly. However, after the server was upgraded and switched the server name in `sys.servers` still had the old server name. I had to drop the old server name and add the new server name to `sys.servers` on the new server ``` sp_dropserver 'Server_A' GO sp_adds...
At first check out that your linked server is in the list by this query ``` select name from sys.servers ``` If it not exists then try to add to the linked server ``` EXEC sp_addlinkedserver @server = 'SERVER_NAME' --or may be server ip address ``` After that login to that linked server by ``` EXEC sp_addlinkedsrv...
Could not find server 'server name' in sys.servers. SQL Server 2014
[ "", "sql", "sql-server", "stored-procedures", "sql-server-2014", "linked-server", "" ]
Is there a way to return result with its order? Sample: Run the following query on the `quiz` table: ``` select q.category_id, q.quiz_id, concat('Quiz ',q.name) name from quiz q where q.category_id = 11 order by q.category_id ASC limit 2 offset 2; ``` Table `quiz` (structure): ``` +-------------+---------+-------+ ...
You need to establish a row number to do this. Doing so means you need a unique field to `order by` to ensure the order of the results. You can get the row number using `user-defined variables` in mysql. Here's an example reordering by `quiz_id`: ``` select * from (select q.category_id, q.quiz_id, @rn := @rn + 1, con...
You can either order by your primary key if you have one such as ``` select q.category_id, q.quiz_id, concat('Quiz ',q.name) name from quiz q where q.category_id = 11 order by q.id, q.category_id ASC limit 2 offset 2; ``` If you don't I suggest you add a primary with [something like this](https://stackoverflow.com/qu...
MySQL: return result with its order
[ "", "mysql", "sql", "" ]
I have a room inventory table each room has one record for each day, but some rooms have double record for a day. I want to query to pull out those id. Inventory\_table => id, roomid, inv\_date....
The following may get you a list of the rooms with duplicates. ``` select id, roomid, inv_date, count(room) from room_inventory group by id, roomid, inv_date having count(room) > 1; ```
``` Select Id, count(*) from inventory_table group by roomid, inv_date having count(*)>1 ```
How to find duplicate record for same date
[ "", "sql", "" ]
I am really having problem trying to sum up a column of one table and then group it according to the data from another table. the only common key that they have is account number. here is the scenario ``` table 1. account_no volume read_date 1 32 12016 2 22 12016 3 20 ...
Try this, This will sum up based on read\_dates and Zones ``` SELECT A.read_date ,B.Zone ,sum(A.volume) SumOfVolume FROM @Table1 A INNER JOIN @Table2 B ON A.account_no = B.account_no GROUP BY A.read_date ,B.Zone ```
You just have to `JOIN` the two tables together and do a `GROUP BY Zone`: ``` SELECT t2.Zone, SUM(volume) AS Total FROM table1 AS t1 INNER JOIN table2 AS t2 ON t1.account_no = t2.account_no GROUP BY t2.Zone ```
how to sum a column from one table and group the sum using data from column of another table
[ "", "sql", "sql-server", "" ]
Need a solution for the following situation: I need to update T1, column Email with the following data: id from T1 + @test.com Result that I need should look like this = 1234@test.com, That number must be an ID from T1 + @test.com For example: ``` table 1 = customer COLUMNS = ID, Email, ``` Need to update the Ema...
Are you looking for something like this? ``` CREATE TABLE T1 (ID INT, OtherData VARCHAR(100),eMail VARCHAR(100)); INSERT INTO T1(id,OtherData) VALUES(1,'Row 1'),(2,'Row 2'),(3, 'Row 3'); SELECT * FROM T1; UPDATE T1 SET eMail= CAST(ID AS VARCHAR(10)) + '@test.com' SELECT * FROM T1; --Clean Up DROP TABLE T1; ``` Th...
``` UPDATE T1 SET [Email] = T2.ID + '@test.com' FROM T2 INNER JOIN T1 ON T2.[key_column] = T1.[foreign_key_column]; ``` Is this what you want ?
Update SQL table usign data from another table + custom text
[ "", "sql", "sql-server", "database", "sql-update", "" ]
In the below query, I'm using Subquery1 and Subquery2 to get Account Number and Account Name. However the first Subquery and second joins same tables except an additional table account\_nameinfo\_t in Subquery 2 to get the account name. Is there a way I avoid selecting from other tables and just use the value of Subque...
It looks like you can simplify this using simple joins rather than subqueries, either in the select list or as inline views: ``` SELECT acct.account_no AS "PARENT ACCOUNT", ant.first_name||' '||ant.last_name AS "ACCOUNT NAME", bgs.rec_id2 AS record_type, bgs.current_bal FROM group_t grp JOIN group_billing_member...
Oracle supports a `WITH` clause which you may find useful: <http://psoug.org/reference/with.html> Essentially, it allows you to create a temporary view within a query that can be accessed multiple times. In your case, the result of your common join can be "factored out" and the result can be reused.
Oracle SQL subquery scalar as input to other subquery
[ "", "sql", "oracle", "" ]
I want to query for values such as: ``` AVOCADOS, GRANDPAS-HASS 70CT 23# ``` ...which may be stored without a comma, such as: ``` AVOCADOS GRANDPAS-HASS 70CT 23# ``` I want to disregard whether the comma exists or not, as long as the rest of the varchar value is identical. How can I query for a commaized value an...
Maybe a bit overkill since it may make just as much sense to just clean the data in the first place, but to make the search hit indexes, you can add the stripped field as a computed column and add an index on it; ``` ALTER TABLE unitproducts ADD desc_search AS REPLACE(description, ',', ''); CREATE INDEX ix_desc_search...
How about ``` WHERE REPLACE(string1, ',', '') = REPLACE(string1, ',', '') ``` or for your specific example ``` WHERE REPLACE(Description,',','') = 'AVOCADOS ABUELOS-HASS 70CT 23#' ``` If you want to put "identical" records first in the result list you can also do ``` ORDER BY (CASE WHEN Description='AVOCADOS ABUEL...
How can I disregard whether commas exist in a string with SQL?
[ "", "sql", "sql-server", "" ]
My goal is to get SQL to check if the row exists, if it does update, if not insert. `FTP_num` is the name of the first column. The SQL Statement is ``` using (SqlCommand cmd = new SqlCommand("IF NOT EXISTS(SELECT ftp_num from Distributor WHERE fpt_num = FTP_num)" " insert FTP_Info set IP=@IP, Port=@Port, UN=@UN, PW=...
Your insert syntax is wrong. It should be something like this: ``` using (SqlCommand cmd = new SqlCommand("IF NOT EXISTS(SELECT 1from Distributor WHERE fpt_num = @FTP_num)" + " insert into FTP_Info (IP, Port, UN, PW, Folder, FTP_num) VALUES(@IP, @Port, @UN, @PW, @Folder @ftp_num)" + ...
Check out the merge statement: <https://technet.microsoft.com/en-us/library/bb522522(v=sql.105).aspx> for SQL Server, <http://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_9016.htm> for Oracle
SQL IF NOT EXISTS INSERT Else Update, based on column ID
[ "", "sql", "sql-server", "sql-server-2014", "" ]
I have a table `Employee` with following Sample Data ``` ID Name Gender 1 Mary F 2 John M 3 Smith M ``` I want to write an Update query that would set Gender to `F` where Gender is `M` and set Gender to `M` where Gender is `F`. How can I do this in single `update` query?
You would simply use `case`: ``` update t set Gender = (case when Gender = 'F' then 'M' else 'F' end) where Gender in ('F', 'M'); ```
We can update by using `CASE` expression. **Query** ``` update Employee set Gender = ( case Gender when 'M' then 'F' when 'F' then 'M' else Gender end ); ```
Update multiple rows of same column
[ "", "sql", "sql-server", "sql-update", "" ]
My data-set inside table `object_type_t` looks something like the following: ``` OBJ_ID PARENT_OBJ OBJECT_TYPE OBJECT_DESC --------- ------------ ------------- ----------------------- ES01 <null> ESTATE Bucks Estate BUI01 ES01 BUILDING Leisure Centre BUI02 ES01 BUI...
The desired output has 3 columns which are determined by object types. In general this could be extended with more columns, one for each possible value for the field `object_type`. Even with the given example data, one could imagine an additional column `apartment_obj`. To make this generic without the need to self-jo...
If I correctly understand your need, maybe you can avoid the tabular view, directly querying your table; Say you want to find all the objects belonging to `BUI01`, you can try: ``` with test(OBJ_ID, PARENT_OBJ, OBJECT_TYPE, OBJECT_DESC) as ( select 'ES01','','ESTATE','Bucks Estate' from dual union all select 'BUI01',...
Fetch object of specified level-type from data hierarchy (Oracle 12 SQL)
[ "", "sql", "oracle", "oracle12c", "" ]
Is there a way to stack/group string/text per user ? data I have ``` USER STATES 1 CA 1 AR 1 IN 2 CA 3 CA 3 NY 4 CA 4 AL 4 SD 4 TX ``` What I need is ``` USER STATES 1 CA / AR / IN 2 ...
I am not an expert but this should work. You may need to modify it a bit per your exact requirement. Hope this helps! ``` CREATE VOLATILE TABLE temp AS ( SELECT USER ...
If Teradata's XML-services are installed there's a function named XMLAGG, which returns a similar result: `CA, AR, IN` ``` SELECT user, TRIM(TRAILING ',' FROM (XMLAGG(TRIM(states)|| ',' /* optionally ORDER BY ...*/) (VARCHAR(10000)))) FROM tab GROUP BY 1 ``` Btw, using recursion will result in huge spool usage, b...
Teradata SQL stack rows per user
[ "", "sql", "teradata", "" ]
I've been getting my hands on apps for a few time now, and I now want to develop an App which will help user manage events. Here's the problem, I have very few knowledge in servers/DB and such. To allow users to log in (and import friends) I count on Facebook API. But I have to manage events and users attending events...
**Choice of database.** Any database can do it, but you need to know that some of them are really expensive, such as SQL Server. You can see the SQL Server pricing [here](https://www.microsoft.com/en/server-cloud/products/sql-server/purchasing.aspx). I'd recommend you [MySQL](https://www.mysql.com/) database if your bu...
Its entirely possible to use a SQL server to do these things, but you might be more comfortable using something like [Firebase](https://www.firebase.com/) or other NoSQL database providers
Create an App that interact with SQL
[ "", "android", "ios", "sql", "sql-server", "" ]