Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have below table ``` create table #t (Id int, Name char) insert into #t values (1, 'A'), (2, 'A'), (3, 'B'), (4, 'B'), (5, 'B'), (6, 'B'), (7, 'C'), (8, 'B'), (9, 'B') ``` I want to count consecutive values in name column ``` +------+------------+ | Name | Repetition | +------+------------+ | A | 2 | ...
One approach is the difference of row numbers: ``` select name, count(*) from (select t.*, (row_number() over (order by id) - row_number() over (partition by name order by id) ) as grp from t ) t group by grp, name; ``` The logic is easiest to understand if you run ...
You could use windowed functions like `LAG` and running total: ``` WITH cte AS ( SELECT Id, Name, grp = SUM(CASE WHEN Name = prev THEN 0 ELSE 1 END) OVER(ORDER BY id) FROM (SELECT *, prev = LAG(Name) OVER(ORDER BY id) FROM t) s ) SELECT name, cnt = COUNT(*) FROM cte GROUP BY grp,name ORDER BY grp; ``` **[db<>fiddle...
Count Number of Consecutive Occurrence of values in Table
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "aggregation", "" ]
I would like to sum two columns "Immo"+"Conso" group by "ID" in order to create a new variable "Mixte". My new variable "Mixte" is as follow: * if one ID has (at least) 1 in "Immo" AND 1 in "Conso" then "Mixte" is yes, otherwise "Mixte" is no. For exemple: ``` Ident | Immo | Conso | Mixte ------------------------...
``` select ident,result=(case when sum(Immo)>0 and sum(Conso)>0 then 'yes' else 'no' end) from tabname (NOLOCK) group by id ```
Use a correlated sub-select: ``` select t1.Ident, t1.Immo, t1.Conso, case when (select max(Immo) + max(Conso) from tablename t2 where t2.Ident = t1.Ident) = 2 then 'yes' else 'no' end as Mixte from tablename t1 ``` `Ident` is a reserved word in ANSI SQL, so you may need to ...
SQL - Sum two columns group by ID
[ "", "sql", "sas", "" ]
I have a table A that looks like this ``` Date Name Value ---------------------------- 2015-01-01 A 12 2015-01-01 B 13 2015-01-01 C 10 2015-01-01 D 9 2015-01-01 E 15 2015-01-01 F 11 2015-01-02 A 1 2015-01-02 B 2 2015-01-02 ...
I found one way of getting the desired results, by writing a row\_number() sub select limit to the desired window size. Which gives each entry per date s.th like this ``` Date Name Value Row_Num --------------------------------------- 2015-01-01 A 12 0 2015-01-01 A 12 ...
You just want `lead()`: ``` select a.*, lead(value) over (partition by name order by date) as value_1, lead(value, 2) over (partition by name order by date) as value_2 from a; ```
JOIN multiple rows to multiple columns in single row Netezza/Postgres
[ "", "sql", "join", "netezza", "" ]
I have been tasked with replacing a costly stored procedure which performs calculations across 10 - 15 tables, some of which contain many millions of rows. The plan is to pre-stage the many computations and store the results in separate tables for speeding reading. Having quickly created these new tables and inserted ...
Have you considered Indexed Views for this? As long as you meet the criteria for creating Indexed Views (no self joins etc) it may well be a good solution. The downsides of Indexed Views are that when the data in underlying tables is changed (delete, update, insert) then it will have to recalculate the indexed view. T...
what is the best practice for keeping these new separate tables up to date? Answer is it depends .Depends on what ..? 1.How frequently you will use those computed values 2.what is the acceptable data latency we to have same kind of reporting where we store computed values in seperate tables and use them in reports...
Pre-Staging Data Solution
[ "", "sql", "sql-server", "" ]
I currently use the following query which takes about 8 minute to return the result due to the volume of data (About 14 months). is there a way I can speed this up please? The database in question is MySQL with InnoDb engine ``` select CUSTOMER as CUST, SUM(IF(PAGE_TYPE = 'C',PAGE_TYPE_COUNT,0)) AS TOTAL_C, ...
Okay, as the table range partition is on EVE\_DATE, the DBMS should easily see which partition to read. So it's all about what index to use then. There is one column you check for equality (`SITE = 'P'`). This should come first in your index. You can then add `EVE_DATE` and `SITE_SERV` in whatever order I guess. Thus ...
I don't have the data so I can't test the speed of this but I think it would be faster. ``` select CUSTOMER as CUST, SUM(PAGE_TYPE_COUNT * (PAGE_TYPE = 'C')) AS TOTAL_C, SUM(PAGE_TYPE_COUNT * (PAGE_TYPE = 'D')) AS TOTAL_D from PAGE_HITS where EVE_DATE >= '2016-01-01' and EVE_DATE <= '2016-01-05...
SQL - speed up query
[ "", "mysql", "sql", "query-optimization", "" ]
I have a table of this structure: ``` ID TaskID ResourceID IsActive --- ----- ---------- -------- 1 51 101 1 2 52 101 1 3 53 101 1 4 51 102 0 5 52 102 0 6 53 102 0 ...
Return a row as long as no other row with same ResourceID has IsActive = 1: ``` select ResourceID from TableName t1 where not exists (select 1 from TableName t2 where t1.ResourceID = t2.ResourceID and t2.IsActive = 1) ``` Perhaps you want to do `select distinct ResourceID` to remo...
``` SELECT ResourceID FROM TableName T WHERE NOT EXISTS ( SELECT * FROM TableName WHERE ResourceID = T.ResourceID AND IsActive = 1 ) ``` Or... ``` SELECT ResourceID FROM TableName GROUP BY ResourceID HAVING MAX(IsActive) = 0 ```
SQL Server groupby two columns
[ "", "sql", "sql-server", "group-by", "" ]
i am trying to run this SQL Query: ``` SELECT avg(response_seconds) as s FROM ( select time_to_sec( timediff( from_unixtime( floor( UNIX_TIMESTAMP(u.datetime)/60 )*60 ), u.datetime) ) ) as response_seconds FROM tickets t JOIN ticket_updates u ON t.ticketnumber = u.ticketnumber WHERE u.type = 'update' an...
`)` the one more extra parenthesis in the `) ) as response_seconds` causing the problem, removing that will solve the problem. For better readability I aligned the code: ``` SELECT avg(response_seconds) AS s FROM ( SELECT time_to_sec( timediff( from_unixtime( ...
Remove the `)` just before `as response_seconds` ``` SELECT avg(response_seconds) as s FROM ( select time_to_sec( timediff( from_unixtime( floor( UNIX_TIMESTAMP(u.datetime)/60 )*60 ), u.datetime) ) as response_seconds FROM tickets t JOIN ticket_updates u ON t.ticketnumber = u.ticketnumber ...
cannot find SQL syntax error
[ "", "mysql", "sql", "" ]
I'm working with SQL Server 2012 and wish to query the following: I've got 2 tables with mostly different columns. (1 table has 10 columns the other has 6 columns). however they both contains a column with ID number and another column of category\_name. 1. The ID numbers may be overlap between the tables (e.g. 1 tabl...
Make your `FULL JOIN ON 1=0` This will prevent rows from combining and ensure that you always get 1 copy of each row from each table. Further explanation: A `FULL JOIN` gets rows from both tables, whether they have a match or not, but when they do match, it combines them on one row. You wanted a full join where you...
This demonstrates how you can use a UNION ALL to combine the row sets from two tables, TableA and TableB, and insert the set into TableC. Create two source tables with some data: ``` CREATE TABLE dbo.TableA ( id int NOT NULL, category_name nvarchar(50) NOT NULL, other_a nvarchar(20) NOT NULL ); CREATE TA...
How to join two tables together and return all rows from both tables, and to merge some of their columns into a single column
[ "", "sql", "sql-server", "database", "join", "" ]
I am able to do this in SSMS. I want to do this in SSOE in VS13.
View the table in Designer mode, right click and try set identity. good luck.
Things to check: If table has already been created, SSMS is default-set to prevent changes like that (which actually drop and re-create the table behind the scenes). If this is the case with you, in SSMS go to Tools -> Options -> Designers -> uncheck "Prevent saving changes that require table re-creation" If it's a n...
Identity Increment in SQL Server object explorer is grayed out. How to set is identity = true in sql server object explorer in VS13?
[ "", "sql", "visual-studio-2013", "sql-server-2012", "" ]
I have a column in my sql table. I am wondering how can I add leading zero to my column when my column's value is less than 10? So for example: ``` number result 1 -> 01 2 -> 02 3 -> 03 4 -> 04 10 -> 10 ```
``` format(number,'00') ``` Version >= 2012
You can use `RIGHT`: ``` SELECT RIGHT('0' + CAST(Number AS VARCHAR(2)), 2) FROM tbl ``` For `Number`s with length > 2, you use a `CASE` expression: ``` SELECT CASE WHEN Number BETWEEN 0 AND 99 THEN RIGHT('0' + CAST(Number AS VARCHAR(2)), 2) ELSE CAST(Number AS VARCHAR(10))...
How to add leading zero when number is less than 10?
[ "", "sql", "sql-server", "" ]
I am getting an error, While I am trying to connect (LocalDB)\MSSQLLocalDB through SQL Server management studio. I also tried to login with default database as master the error is same. [![enter image description here](https://i.stack.imgur.com/Q3Gyb.png)](https://i.stack.imgur.com/Q3Gyb.png) Here is the Server detail...
**Warning: this will delete all your databases located in MSSQLLocalDB. Proceed with caution.** The following command through sqllocaldb utility works for me. ``` sqllocaldb stop mssqllocaldb sqllocaldb delete mssqllocaldb sqllocaldb start "MSSQLLocalDB" ``` [![enter image description here](https://i.stack.imgur.com...
For this particular error, what gave me access to my MDF in VS2019 was: 1. In Solution Explorer, right click your MDF file 2. Detach That was it and I now have access. I was expecting to detach and attach, but that wasn't needed. I also could not get to my (localdb) in SSMS either, so what helped me there was a solu...
Cannot connect to (LocalDB)\MSSQLLocalDB -> Login failed for user 'User-PC\User'
[ "", "sql", "sql-server", "ssms", "localdb", "" ]
I'm using a Crystal Reports 13 Add Command for record selection from an Oracle database connected through the Oracle 11g Client. The error I am receiving is ORA-00933: SQL command not properly ended, but I can't find anything the matter with my code (incomplete): ``` /* Determine units with billing code effective dat...
If the `where` before `Join` really matters to you, use a CTE. (Employing `with` clause for temporary table and joining on the same.) ``` With c as (SELECT "UNITS"."UnitNumber", "BILL"."EFF_DT","BILL"."UNIT_ID" -- Correction: Was " BILL"."UNIT_ID" (spacetanker) FROM "MFIVE"."BILL_UNIT_ACCT" "BILL" -- Returning...
You have a `WHERE` clause before the `INNER JOIN` clause. This is invalid syntax - if you swap them it should work: ``` SELECT "UNITS"."UnitNumber", "BILL"."EFF_DT" FROM "MFIVE"."BILL_UNIT_ACCT" "BILL" LEFT OUTER JOIN "MFIVE"."VIEW_ALL_UNITS" "UNITS" ON "BILL"."UNIT_ID" = "UNITS"."UNITID"...
SQL Command Not Properly Ended - Oracle Subquery
[ "", "sql", "oracle", "oracle11g", "crystal-reports", "" ]
I get this message `column "mi.*" must appear in the GROUP BY clause or be used in an aggregate function` what does that means? and how to solve it? I tried change `GROUP BY m.id` to `GROUP BY m.id, mi.media_id` still same error I test this if I remove `GROUP BY m.id ORDER BY COUNT(mua.id)` it works data structure ...
You can get the grouping first and then do a join like ``` SELECT m.*, row_to_json(mi.*) as media_information FROM media m LEFT JOIN media_information mi ON mi.media_id = m.id LEFT JOIN (select media_id, COUNT(id) as mua_count from media_user_action group by media_id) xxx ON xxx.m...
Do group by in subselect. I don't have your structure - so perhaps it wouldn't work - so please treat is as a sample: ``` SELECT m.*, row_to_json(mi.*) as media_information FROM media m JOIN media_information mi ON mi.media_id = m.id JOIN media_user_action mua ON mua.media_id = m.id JOIN ( SELECT m.id, coun...
select row_to_json table, error: must appear in the GROUP BY clause or be used in an aggregate function
[ "", "sql", "postgresql", "" ]
I have a table looks like: ``` user key x 1 x 2 y 1 z 1 ``` The question is simple. How to find out which one is the user who has not key 2? The result should be y and z users.
@jarlh's answer is likely the fastest if you have ***two*** tables; - One with the users - One with your facts ``` select "users"."user_id" from "users" where not exists (select 1 from tablename t2 where t2."user_id" = "users"."user_id" and t2."key" = 2) ``` That's the stru...
Return a user row as long as the same user doesn't have another row with key 2. ``` select user, key from tablename t1 where not exists (select 1 from tablename t2 where t2.user = t1.user and t2.key = 2) ``` Note that `user` is a reserved word in ANSI SQL, so you may need to deli...
PostgreSQL selection
[ "", "sql", "postgresql", "" ]
Is there anything wrong with this statement? ``` SELECT * FROM Movies INNER JOIN Sessions ON Movies.MovieID=Sessions.MovieID INNER JOIN Tickets ON Sessions.SessionID=Tickets.SessionID; ``` When ever I run it on Access I get a Syntax error 'Missing Operator'. Also are there any alternatives to Acc...
In general, no. In MS Access, yes. It likes extra parentheses, probably because the database developers don't believe in readability: ``` SELECT * FROM (Movies INNER JOIN Sessions ON Movies.MovieID = Sessions.MovieID ) INNER JOIN Tickets ON Sessions.SessionID = Tickets.SessionID; ```
You could enable OPENROWSET if you have a local instance of SQL, and install MDACs (I would install both x86 and x64 if you have a 64 bit pc). Below is a link to an article that will help you get setup. Also, be sure to run the management studio with elevated privileges. [How to enable Ad Hoc Distributed Queries](http...
SQL error Statement, Missing Operator
[ "", "sql", "ms-access", "" ]
I encountered many times this problem of decimal in MySQL ! When i put this type: `DECIMAL(10,8)` The maximum value allowed are: `99.99999999` ! It supposed to be: `9999999999.99999999` no ? I want a maximum value of decimal with 8 digits after the point (.).
From the [documentation](https://dev.mysql.com/doc/refman/5.7/en/precision-math-decimal-characteristics.html): > The declaration syntax for a DECIMAL column is DECIMAL(M,D). The ranges of values for the arguments in MySQL 5.7 are as follows: > > * M is the maximum number of digits (the precision). It has a range of 1 ...
A `decimal` is defined by two parameters - `DECIMAL(M, D)`, where `M` is the total number of digits, and `D` is number of digits after the decimal point **out of `M`**. To properly represent the number `9999999999.99999999`, you'd need to use `DECIMAL(18, 8)`.
encountered many times this difficulty of decimal in MySQL
[ "", "mysql", "sql", "ddl", "" ]
I have two tables (1. orders and 2. cars): **Cars** [![Cars](https://i.stack.imgur.com/N9Lfp.png)](https://i.stack.imgur.com/N9Lfp.png) **Orders** [![Orders](https://i.stack.imgur.com/saM9O.png)](https://i.stack.imgur.com/saM9O.png) I'm trying to find all cars that are available at a given date. In this case I wan...
Let's say you have 2 periods T1 and T2 to check to see if they overlap you do this check (T1.start <= T2.end) AND (T1.end >= T2.start). so try this below query, (it checks and makes sure that there doesn't exist an order of the same car that overlap the specified period ``` SET @startdate = '2016-05-03',@enddate = '2...
Change your thinking from exclusionary: ``` date_to NOT BETWEEN '2016-05-03' AND '2016-05-05' AND date_from NOT BETWEEN '2016-05-03' AND '2016-05-05' ``` to inclusionary: ``` (date_from < '2016-05-03' AND date_to < '2016-05-05') OR (date_from > '2016-05-03' AND date_to > '2016-05-05') ```
Find available dates
[ "", "mysql", "sql", "date", "" ]
I am struggling with a TSQL query and I'm all out of googling, so naturally I figured I might as well ask on SO. Please keep in mind that I just began trying to learn SQL a few weeks back and I'm not really sure what rules there are and how you can and can not write your queries / sub-queries. This is what I have so ...
artm's query corrected (PARTITION) and the last step (pivoting) simplified. ``` with data AS (select '2016-01-01' as called, '111' as number union all select '2016-01-01', '111' union all select '2016-01-01', '111' union all select '2016-01-01', '222' union all select '2016-01-01', '222' union all select '2016-01-05',...
Interesting one this, I believe you can do it with a CTE and PIVOT but this is off the top of my head... This may not work verbatim ``` WITH Rollup_CTE AS ( SELECT Client,MONTH(Date) as Month, YEAR(Date) as Year, Number, Count(0) as Calls, ROW_NUMBER() OVER (PARTITION BY Client,MONTH(Date) as SqNo, YEAR(Date), Num...
How do I select the most frequent value for a specific month and display this value as well as the amount of times it occurs?
[ "", "sql", "sql-server", "t-sql", "ssms", "" ]
``` SELECT ShopOrder.OrderDate , Book.BookID , Book.title , COUNT(ShopOrder.ShopOrderID) AS "Total number of order" , SUM (Orderline.Quantity) AS "Total quantity" , Orderline.UnitSellingPrice * Orderline.Quantity AS "Total order value" , book.Price * Orderline.Quantity AS "Total retail value" FROM ShopOrder ...
You need to extract the year and month from the date and use those in the `select` and `group by` columns. How you do this depends highly on the database. Many support functions called `year()` and `month()`. Then you need to just aggregate by the fields that you want. Something like this: ``` SELECT YEAR(so.OrderDat...
For group, you can use datepart function ``` GROUP BY (DATEPART(yyyy, ShopOrder.OrderDate), DATEPART(mm, ShopOrder.OrderDate)) ```
SQL sorting date by year and month
[ "", "sql", "pgadmin", "" ]
I have a table with columns mentioned below: ``` transaction_type transaction_number amount Sale 2016040433 50 Cancel R2016040433 -50 Sale 2016040434 50 Sale 2016040435 50 Cancel R2016040435 -50 Sale ...
If you just want to count the sales and subtract the cancels (as suggested by your sample data), you can use conditional aggregation: ``` select sum(case when transaction_type = 'Sale' then 1 when transaction_type = 'Cancel' then -1 else 0 end) from t; ```
``` SELECT count(transaction_type) FROM TBL_NAME GROUP BY count(transaction_type) HAVING transaction_type = 'Sale' ``` Just use the count function, and use HAVING with GROUP BY to filter
How to find net rows from sales and cancel rows using sql
[ "", "sql", "" ]
I have a table like below ``` event_date id ---------- --- 2015-11-18 x1 2015-11-18 x2 2015-11-18 x3 2015-11-18 x4 2015-11-18 x5 2015-11-19 x1 2015-11-19 x2 2015-11-19 y1 2015-11-19 y2 2015-11-19 y3 2015-11-20 x1 2015-11-20 y1 2015-11-20 z1 2015-11-20 z2 ``` **Qu...
Here is an answer that'll work although I am not sure I like it: ``` select t.event_date, count(1) from ( -- Record first occurrence of each id along with the earliest date occurred select id, min(event_date) as event_date from mytable group by id ) t group...
You could group by the date and apply a distinct count to the id per group: ``` SELECT event_date, COUNT(DISTINCT id) FROM mytable GROUP BY event_date ```
how to get unique values in SQL?
[ "", "sql", "postgresql", "count", "" ]
I just stumbled across this gem in our code: ``` my $str_rep="lower(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(field,'-',''),'',''),'.',''),'_',''),'+',''),',',''),':',''),';',''),'/',''),'|',''),'\',''),'*',''),'~','')) like lower('%var%')"; ``` I'm not re...
It depends on the DBMS you are using. I'll post some examples (feel free to edit this answer to add more). ## MySQL There is really not much to do; the only way to replace all the characters is nesting `REPLACE` functions as it has already been done in your code. ## Oracle DB Your clause can be rewritten by using t...
Your flagged this as *Perl*, but it's probably not? Here is a Perl solution anyway: ``` $var =~ s/[\-\.\_\+\,\:\;\/\|\\\*\~]+//g; ```
Rewrite this exceedingly long query
[ "", "sql", "firebird", "firebird2.5", "" ]
I met the following MySQL code: ``` SELECT ServiceFee FROM Shows WHERE ID = (SELECT ShowID FROM Orders WHERE ID = ?) ``` It makes me wonder because the people who wrote this code usually use SQL joins. I would rewrite it ``` SELECT ServiceFee FROM Shows INNER JOIN Orders ON Shows.ID = Orders.ShowID WHERE Orders.ID =...
Nope, there are no caveats. As a matter of fact, the [`INNER JOIN`](http://www.codersrevolution.com/blog/MySQL-performance-INNER-JOIN-vs-subselect) query might run faster
"Is there any reason why this code was written with a subquery" a very long time ago MySQL joins used to be slow
Weird SQL code: Why do they use a subquery instead of join?
[ "", "mysql", "sql", "join", "subquery", "" ]
In a database I have two linked tables that store records of fish landings. A business required is that these landings are priced once a week and then posted a week later to allow those individuals for whom payment will then be made to check the paperwork. The system has generally worked well over the years but last we...
The most straightforward method would be to wrap your query with an outer query that utilizes a [HAVING clause](https://msdn.microsoft.com/en-us/library/ms180199.aspx): ``` SELECT q.ProductId FROM ( SELECT DISTINCT ld.ProductId, ld.UnitPrice FROM LandingDetails ld JOIN LandingHeaders lh ON ld.Landing...
``` SELECT ld.ProductId FROM LandingDetails ld JOIN LandingHeaders lh ON ld.LandingId = lh.LandingId WHERE lh.LandingDate1 BETWEEN '20160313' AND '20160319' GROUP BY ld.ProductId HAVING COUNT(DISTINCT ld.UnitPrice)>1 ```
What is the most efficient way to identify rows with differing values
[ "", "sql", "sql-server-2014", "" ]
In my attempts to edit a procedure using the line ``` CREATE OR DROP PROCEDURE ``` I have created two procedures with the same name, how can I delete them? The error I receive whenever I attempt to drop it is > Reference to Rountine BT\_CU\_ODOMETER was made without a signature, but the routine is not unique in its...
Assuming this is DB2 for LUW. DB2 allows you to "overload" procedures with the same name but different number of parameters. Each procedure receives a *specific name*, which can be provided by you or generated by the system and which will be unique. To determine the specific names of your procedures, run ``` SELECT ...
**PROBLEM** When multiple stored procedures are created with the same name but with a different number of parameters, then the stored procedure is considered overloaded. When attempting to drop an overloaded stored procedure using the DROP PROCEDURE statement, the following error could result: ``` db2 drop procedure ...
Deleting a non-unique procedure on DB2
[ "", "sql", "db2", "procedure", "" ]
I have an order\_transactions table with 3 relevant columns. `id` (unique id for the transaction attempt), `order_id` (the id of the order for which the attempt is being made), and `success` an int which is 0 if failed, and 1 if successful. There can be 0 or more failed transactions before a successful transaction, fo...
To get the number of orders which never had a successful transaction you can use: ``` SELECT COUNT(*) FROM ( SELECT order_id FROM transactions GROUP BY order_id HAVING COUNT(CASE WHEN success = 1 THEN 1 END) = 0) AS t ``` [**Demo here**](http://sqlfiddle.com/#!9/0bcbf4/5) The number of orders which had a tr...
You want "counts" of orders that meet specific conditions over multiple rows, so I'd start with a GROUP BY order\_id ``` SELECT ... FROM mytable t GROUP BY t.order_id ``` To find out if a particular order ever had a failed transaction, etc. we can use aggregates on expressions that "test" for conditions. For exa...
MySQL -- Finding % of orders with a transaction failure
[ "", "mysql", "sql", "select", "" ]
I've got 3 tables. Companies, Kommuner and Fylker. The companies table have an empty field `forretningsadresse_fylke` but an other field `forretningsadresse_kommune` with a value. So basically, I need to fill in `forretningsadresse_fylke`, based on the value of `forretningsadresse_kommune`. Now, the value of `forret...
You do not want `fylker` in the `UPDATE` statement. You should also be using a proper `join`. So the first rewrite is: ``` UPDATE companies c JOIN kommuner k ON c.forretningsadresse_kommune = k.kommuneNavn SET c.forretningsadresse_fylke = (SELECT f.fylkeNavn FRO...
you can refer this question <https://stackoverflow.com/questions/15209414/how-to-use-join-in-update-query> ``` UPDATE companies c JOIN Kommuner k ON c.kommuneID = k.kommuneID JOIN fylker f ON f.fylkeID = k.fylkeID SET c.forretningsadresse_fylke = f.fylkeNavn ```
MySQL update with select from another table
[ "", "mysql", "sql", "" ]
I am using SQL Server 2014 and I need to add a line to my SQL query that will convert a column called StayDate into the "MMM YYYY" format. The StayDate column is in `datetime` format (eg: 2016-06-01 00:00:00.000) Basically, I need the output to be "Jul 2016" (from example above). I have tried playing around with the ...
The `format` function takes a .NET format string, so the four digit year part has to be in lowercase, like this: ``` Format(StayDate, "MMM yyyy") ``` (reference: <https://msdn.microsoft.com/de-de/library/hh213505(v=sql.120).aspx>)
Try this ``` DECLARE @SYSDATE DATETIME = '2016-06-01 00:00:00.000' SELECT RIGHT(CONVERT(VARCHAR(11), @SYSDATE, 106) ,8) --OR SELECT LEFT(DATENAME(MONTH, @SYSDATE), 3) + ' ' + DATENAME(YEAR, @SYSDATE) ```
What is the most simple T-SQL syntax to convert a datetime column into the 'MMM YYYY" format?
[ "", "sql", "sql-server", "t-sql", "date", "datetime", "" ]
in this select i need the sum result the IIF expression, but when i execute this query obtain only first IIF statement. Any suggestion?? Thanks ``` SELECT conto, desconto, date, codoperaio, SUM(IIF(totcasse ='1',SUM(totcasse),0)+ IIF(totcasse ='6',SUM(totcasse*3),0)+ ...
If am not wrong you are looking for this ``` SELECT conto, desconto, date, codoperaio, Sum(CASE totcasse WHEN '1' THEN totcasse ELSE 0 END) + Sum(CASE totcasse WHEN '6' THEN totcasse * 3 ELSE 0 END) + Sum(CASE totcasse WHEN '8' THEN totcasse * 4 ELSE 0 END) + Sum(CAS...
``` SELECT conto, desconto, date, codoperaio, IIF(totcasse ='1',SUM(totcasse),0)+ IIF(totcasse ='6',SUM(totcasse*3),0)+ IIF(totcasse ='8',SUM(totcasse*4),0)+ IIF(totcasse ='10',SUM(t...
SUM IIF expression result
[ "", "sql", "sql-server", "" ]
I am using SQL Server 2014 and I need to add a line of code to my SQL query that will filter the data extracted only to those records where the `StayDate` (a column in database) is `greater than or equal to` the `1st day of the current month`. In other words, the line of code I need is the following: ``` WHERE StayDa...
Use [**`EOMONTH`**](https://msdn.microsoft.com/en-IN/library/hh213020.aspx) to get the first day of current month ``` WHERE StayDate >= Dateadd(dd, 1, Eomonth(Getdate(), -1)) ```
SQL Server 2012 and above ``` WHERE StayDate >= DATEADD(DAY, 1, EOMONTH(GETDATE(), -1)) ``` Before SQL Server 2012 ``` WHERE StayDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) ```
T-SQL syntax to filter records where the datetime variable is greater than or equal to the 1st Day of the Current Month
[ "", "sql", "sql-server", "t-sql", "datetime", "sql-server-2014", "" ]
I use below code but doesn't return what I expect, the table relationship, each `gallery` is include multiple `media` and each media is include multiple `media_user_action`. I want to count each `gallery` how many `media_user_action` and order by this count ``` rows: [ { "id": 1 }, { "id": 2 } ] ``` and ...
The join with *gallery\_media* table is multiplying your results. The count and grouping should happen after you have made that join. You could achieve that like this: ``` SELECT g.id, COUNT(DISTINCT mua.media_id) FROM gallery g LEFT JOIN gallery_media gm ON gm.gallery_id = g.id LEFT JOIN med...
You're grouping by `media_id` to get a count, but since one `gallery` can have many `gallery_media`, you still end up with multiple rows for one `gallery`. You can either sum the `mua_count` from your subselect: ``` SELECT g.*, sum(mua_count) FROM gallery g LEFT JOIN gallery_media gm ON gm.gallery_id = g.id LEFT JOIN...
group twice in one query
[ "", "sql", "postgresql", "join", "group-by", "" ]
I have a SQL Server table with a few columns. One of those columns is a `date` and another is `No of Nights`. Number of nights is always a two character `varchar` column with values like 1N, 2N, 3N etc depending on the number of nights up to 7N. I want to subtract the 1 part of the 1N column from the date. For ex: ...
``` SELECT DATEADD ( DAY, - CONVERT(INT, REPLACE(NoofNights, 'N', '')), getdate() ) as Result ```
Try this ``` DECLARE @V_Date DATETIME = '2016-04-26 00:00:00.000' ,@V_NoofNIghts VARCHAR(2) = '1N' SELECT DATEADD(DAY, CAST(LEFT(@V_NoofNIghts,1) AS INT) *-1 ,@V_Date) ```
Date subtraction error
[ "", "sql", "sql-server", "" ]
I want to delete specific values/data from one column with the `WHERE` condition. Table `CIVILITE`: ``` ID_CIVILITE CIV_LIBELLE 1 M. 2 Mme 3 Mlle 4 Aucun DELETE FROM CIVILITE WHERE CIV_LIBELLE='Aucun'; ``` Error: > The DELETE statement is in conflict with the constraint REFE...
The reason why you are getting this error is because you are trying to delete a row which is being referenced by another row hence resulting in the error. So either delete the reference row or remove the constraint temporarily. You need to first alter your table like this: ``` ALTER TABLE [DBDB].[dbo].[PERSONNE] NOCHE...
Seems table CIVILITE column ID\_CIVILITE is a primary key, first delete the similar rows in referenced table i.e foreign key table. ``` -- Run 1st DELETE FROM [PERSONNE] WHERE ID_CIVILITE IN (SELECT CIVILITE WHERE CIV_LIBELLE='Aucun') -- Run 2nd DELETE CIVILITE WHERE CIV_LIBELLE='Aucun' ```
Delete specific values from column
[ "", "sql", "sql-server", "sql-delete", "" ]
I am trying to export from my `Table` data into `Excel` through `T-SQL` query. After little research I came up with this ``` INSERT INTO OPENROWSET ('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=G:\Test.xls;', 'SELECT * FROM [Sheet1$]') SELECT * FROM dbo.products ...
I have MS Sql server 2012, and Office 2013. This seems to be very finicky, so you may have to adjust to your particular versions. 1. Download the Microsoft.ACE.OLEDB.12.0 for Windows, 64 bit version found here: <https://www.microsoft.com/en-us/download/details.aspx?id=13255> 2. Install it on your server. 3. Check the ...
Check out sp\_configure /RECONFIGURE... ``` sp_configure 'show advanced options', 1; GO RECONFIGURE; GO sp_configure 'Ad Hoc Distributed Queries', 1; GO RECONFIGURE; GO ``` See these links for more info: <https://technet.microsoft.com/en-us/library/aa259616(v=sql.80).aspx> <http://blog.sqlauthority.com/2010/11/03/s...
Cannot create an instance of OLE DB provider Microsoft.Jet.OLEDB.4.0 for linked server null
[ "", "sql", "sql-server", "export-to-excel", "openrowset", "" ]
In this part of query: ``` . . . WHERE col <> 10 ``` It matches everything except `10` and `NULL`. While I want to match everything except only `10`. So how can I exclude `NULL` of that?
This you can use for MySQL, ``` ...WHERE IFNULL(col,0) <> 10 ``` If the value of col is `NULL` then `IFNULL(col,0)` will convert the value to `'0'` and perform the comparison. So you will get all the records except only `10`.
The problem is that the condition `col != 10` (in MySQL) means "row where `col` has a value that is not 10". `NULL` is not a value so `NULL` rows aren't matched. If they were, you could have problems with `NULL`s cascading into other parts of your logic messing things up, since they don't use the same equality logic as...
How can I exclude NULL of not equal operator?
[ "", "mysql", "sql", "operators", "where-clause", "" ]
I would like to include a column row\_number in my result set with the row number sequence, where 1 is the newest item, without gaps. This works: ``` SELECT id, row_number() over (ORDER BY id desc) AS row_number, title FROM mytable WHERE group_id = 10; ``` Now I would like to query for the same data in chunks of 1000...
Assuming: * `id` is defined as `PRIMARY KEY` - which means `UNIQUE` and `NOT NULL`. Else you may have to deal with NULL values and / or duplicates (ties). * You have no concurrent write access on the table - or you don't care what happens after you have taken your snapshot. A [`MATERIALIZED VIEW`](https://www.postgre...
You want to have a query for the first 1000 rows, then one for the next 1000, and so on? Usually you just write one query (the one you already use), have your app fetch 1000 records, do something with them, then fetch the next 1000 and so on. No need for separate queries, hence. However, it would be rather easy to wr...
Global row numbers in chunked query
[ "", "sql", "postgresql", "pagination", "row-number", "postgresql-9.4", "" ]
I want to make a select query which groups rows based on a given column and then sorts by size of such groups. Let's say we have this sample data: ``` id type 1 c 2 b 3 b 4 a 5 c 6 b ``` **I want to obtain the following** by grouping and sorting the column 'type' in a descending way: ``` id type 2 b 3...
It may not be the best way, but it will give you what you want. You work out the totals for each group and then join that "virtual" table to your original table by the determined counts. ``` SELECT * FROM sampletable s1 INNER JOIN (SELECT count(type) AS iCount,type FROM sampletable GROUP BY type) s2 O...
You can't use a column alias in your `GROUP BY`; just repeat the expression: ``` SELECT type, COUNT(type) AS count FROM sampletable GROUP BY type ORDER BY COUNT(*) DESC, type ASC ``` Note that I changed the `SELECT` clause - you can't use `*` in your `SELECT` either since expressions in the `SELECT` need to either...
SQL Sort by group size
[ "", "sql", "" ]
Using SQL-Server. I have a table AVQ. Two of the columns are named Questions and Instructions. I would like to concatenate those two columns and store the result back into Questions. I've got the concat query `SELECT question + ISNULL(' ' + instructions, '') from AVQ;` But I'm unsure of how to get the result back in...
Sub-query isn't required here. ``` update AVQ set Question = question + ISNULL(' ' + instructions, '') where AVID = 2; ```
Here is a method that might actually be more efficient: ``` update AVG set Question = Question + ' ' + instructions where AVID = 2 and instructions is not null; ``` Why bother even attempting to do the update if `instructions` is empty?
Insert concat of two columns back into one of the original columns
[ "", "sql", "sql-server", "" ]
I have two tables both of which have the same two columns: feature ID and language. I want to pull out records where the language has changed for the feature ID. The problem, though, is that there are multiple languages for each feature ID. My tables look like: Table 1 ``` Feature ID | Language ---------------------...
``` SELECT a.feature_id, b.feature_id, a.language, b.language FROM [table 1] a FULL OUTER JOIN [table 2] b on a.feature_id = b.feature_id and a.language = b.language WHERE a.feature_id is null or b.feature_id is null ``` Change it to a full outer join on language and feature and then a where clause to filter down...
Try this: ``` SELECT a.feature_id, b.feature_id, a.language, b.language FROM table 1 a FULL OUTER JOIN table 2 b on a.feature_id = b.feature_id WHERE a.feature_id || a.language <> b.feature_id || b.language ``` Or: ``` SELECT a.feature_id, b.feature_id, a.language, b.language FROM table 1 a LEFT OUTER JOIN table ...
SQL: Find diff between two tables with non-unique feature IDs?
[ "", "sql", "" ]
I keep getting a syntax error, I've look at countless examples I'm not sure what the problem is... ``` DELIMITER // CREATE PROCEDURE test() BEGIN SELECT * FROM user; END // DELIMITER ; ``` SCREENSHOT: [![enter image description here](https://i.stack.imgur.com/IjsI7.png)](https://i.stack.imgur.com/IjsI7.png)
Alter procedure and remove delimiter....like below ``` CREATE PROCEDURE test() BEGIN SELECT * FROM user; END ```
Modify the user to [user] as user is reserved keyword ``` CREATE PROCEDURE test() BEGIN SELECT * FROM [user]; END ```
creating stored procedure - syntax error
[ "", "mysql", "sql", "stored-procedures", "" ]
I am using SQL Server 2008 and I have two columns in date format: ``` Column_1: [2014-12-19] Column_2: [2015-08-31] ``` I want to merge them and change the the data type to `NVARCHAR`. I tried this code ``` CONVERT(NVARCHAR,[ Column_1])+CONVERT(NVARCHAR,[Column_2])AS TEST ``` but I get this result: ``` 2014-12-19...
Although you can fiddle around with conversion codes, just use replace: ``` REPLACE(CONVERT(NVARCHAR(255), Column_1) + CONVERT(NVARCHAR(255), Column_2), '-', '') AS TEST ``` Or, if you don't want to be dependent on the local date format: ``` CONVERT(NVARCHAR(255), Column_1, 112) + CONVERT(NVARCHAR(255), Column_2, 11...
`CONVERT` has a third parameter which determines the format of the date/time. See [here](https://msdn.microsoft.com/en-GB/library/ms187928.aspx?f=255&MSPPError=-2147217396) for definition. Code 112 will give you what you want. You can also use `REPLACE` to remove the hyphens.
Convert date to nvarchar and merge two columns
[ "", "sql", "sql-server", "" ]
I'm trying to calculate the variation of two values between current month and the previous one. let's say I have a total calls in different months and and want to have the variation for each month from the previous one. U have a table contains vendor, month and calls in each month I have tried the following query nut i...
thank you all for your answers, I have came up with a solution for this, I created a temp table and join it on vendor and month with previous month as following: ``` select vendor,month, nvl(round(sum(calls),2),0.0) as "total_calls" into temp1 from table_summary group by month,vendor order by month,vendor select tb1....
It's difficult to say without seeing your data and desired results, but perhaps you might be better of just going with a self join instead of window functions: ``` SELECT month_summary.vendor, month_summary.calls, month_summary.calls - prev_month_summary.calls / prev_month_summary.calls) as tot_calls_varia...
Calculate the variation of values in amazon redshift database
[ "", "sql", "amazon-redshift", "" ]
I have a table which save xml data. The xml is as follows ``` <responses> <response> <id>UniqueRowID</id> <value>16</value> </response> <response> <id>Language</id> <value>en-GB</value> </response> <response> <id>UserId</id> <value>21</value> </response> </responses> ``` In next co...
I place this as second answer as it is a completely different approach. With this code you can read any XML of this structure. Using dynamic SQL makes it possible to create dynamic column names: ``` CREATE TABLE #tmpTbl (YourXml XML); INSERT INTO #tmpTbl VALUES ('<responses> <response> <id>UniqueRowID</id> <...
This is a simple XML structure. If you need to "flatten" it into a SQL table, you can do so with XPATH syntax as shown below. ``` declare @xml xml = ' <responses> <response> <id>UniqueRowID</id> <value>16</value> </response> <response> <id>Language</id> <value>en-GB</value> </response> <respo...
Xml to table in tsql
[ "", "sql", "xml", "t-sql", "" ]
* 1. The difference of the two statements? * 2. Is the second statemnet faster than the first statement? First statement : ``` SELECT * FROM students WHERE id = 2197176; SELECT * FROM students WHERE id = 74877; ``` Second statement: ``` SELECT * FROM students WHERE id IN(2197176, 74877, ...) ``` **UPDATE**: * 3. ...
I ran execution plan on 3 different queries. First query: Using `UNION` Second query: Using `UNION ALL` Third query: Using `IN` ``` USE AdventureWorksLT2012 -- First query using UNION SELECT ProductID, Name FROM SalesLT.Product WHERE ProductID = 716 UNION SELECT ProductID, Name FROM SalesLT.Product WHERE ProductID...
First query ``` SELECT * FROM students WHERE id = 2197176 .. ``` returns rows with an id column value equal with specific value in this case 2197176 multiple select returns union of results. In the second query ``` SELECT * FROM students WHERE id IN (2197176, 74877, ...); ``` returns rows where the id column value...
What's the difference of SELECT and SELECT IN in sql?
[ "", "sql", "" ]
So what I'm looking to do is create a report that shows how many sales a company had on a weekly basis. So we have a time field called `created` that looks like this: ``` 2016-04-06 20:58:06 UTC ``` This field represents when the sale takes place. Now lets say I wanted to create a report that gives you how many sal...
you can use [WEEK()](https://cloud.google.com/bigquery/query-reference#week) function - it gives you week number ``` SELECT WEEK('2016-04-06 20:58:06 UTC') ``` if you need first day of the week - you can try something like ``` STRFTIME_UTC_USEC((UTC_USEC_TO_WEEK(TIMESTAMP_TO_USEC(TIMESTAMP('2016-05-02 20:58:06 UTC')...
The documentation advises to use standard SQL functions, like [DATE\_TRUNC()](https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions): ``` SELECT DATE_TRUNC(DATE '2019-12-25', WEEK) as week; ```
Best way to break down by weeks in BigQuery
[ "", "sql", "google-bigquery", "bigdata", "" ]
I am looking for the detail answer with simple examples of these functions.
**NVL** checks if first argument is null and returns second argument: ``` select nvl(null, 'arg2') from dual ``` in this example result will be: arg2; ``` select nvl('arg1', 'arg2') from dual ``` and in this one: arg1; **NVL2** has different logic. If first argument is not null then NVL2 returns second argument, b...
Both the NVL(exp1, exp2) and NVL2(exp1, exp2, exp3) functions check the value exp1 to see if it is null. With the NVL(exp1, exp2) function, if exp1 is not null, then the value of exp1 is returned; otherwise, the value of exp2 is returned, but case to the same data type as that of exp1. With the NVL2(exp1, exp2, exp3)...
What are the NVL and the NVL2 functions in Oracle? How do they differ?
[ "", "sql", "oracle", "" ]
My requirement is to retrieve all the employee names from `employees` table and if there are no matching rows in `employee` table then employee name should be displayed along with the count as 0 ``` CREATE TABLE #EMPLOYEES ( employeeId int, employeename varchar(50) ) INSERT INTO #EMPLOYEES VALUES (1,'Dinesh A...
Try this: ``` SELECT te.employeeID, employeeName, (SELECT COUNT(*) FROM #LOGS Tee WHERE Te.employeeID = Tee.employeeID AND Tee.entityCode = 201) AS caseEntryCount FROM #EMPLOYEES Te ORDER BY Te.employeeID ``` You can rewrite your query with a LEFT OUTER JOIN using a GROUP BY but is more slow than a simple q...
Try this. ``` SELECT e.* , COUNT(l.entityID) AS CaseEntry FROM #EMPLOYEES e LEFT JOIN #LOGS l ON l.employeeID = e.employeeId GROUP BY e.employeeId , e.employeename , l.EntityCode ORDER BY e.employeeId; ``` Try to avoid using ORDER BY if the order doesn't matter. That would give you better performanc...
How to get all columns from first table when there is no matching column in SQL Server 2012
[ "", "sql", "sql-server", "sql-server-2008", "sql-server-2012", "" ]
I have the following table for student's fee payments ``` [fee_id] INT [user_id] INT [payment] DECIMAL (18, 2) [date] DATETIME [fee_remaining] DECIMAL (18, 2) [year] INT [payment_method] NVARCHAR (50) [fee_required] DECIMAL (...
Use a `case` expression to assign the required status to each row and `group by` the calculated column. ``` select status, count(*) as total from ( SELECT case when fee_remaining = 0 then 'fully_paid' when fee_remaining <> fee_required then 'partially_paid' when fee_remaining = fee_required then 'unpaid' ...
So without *completely* restructuring your query into something more efficient like [kvp's answer](https://stackoverflow.com/a/36990923/74757), you could `UNION` each of the results instead of using them each as a sub-query: ``` SELECT 'Fully Paid' AS Status, COUNT(*) AS Total FROM fee_payments WHERE (fee_remaining = ...
Rewrite SQL query to return rows for each dataset
[ "", "sql", "sql-server", "dataset", "" ]
I need to check whether the column middle name contain any value or not. If it is empty, then it should not be concatenated with the name. ``` Select .. Agent, FirstName + ' ' MiddleName + ' ' + LastName as Name, ... from tbSystemUser ``` In above query it adds space two times in Name if ...
You could use `CASE expression` with `COALESCE` in following: ``` select .. Agent, case when coalesce(MiddleName, '') = '' then FirstName + ' ' + LastName else FirstName + ' ' + MiddleName + ' ' + LastName end as Name, ... from tbSystemUser ```
You can use case statement ``` Select .. Agent, Case MiddleName when ' ' then FirstName + ' ' + LastName else FirstName + ' ' MiddleName + ' ' + LastName end as Name, ... from tbSystemUser ``` OR ``` Select .. Agent, Case wh...
How to check values in column in Select query
[ "", "sql", "sql-server", "" ]
In my stored procedure, i am having several parameters which in case if one of them is filled some of them will be ignored and vise versa. ``` create procedure FlightReservations @resDate date = getdate, @fromdate date = null, @todate date = null, -- few...
Note that checking against null should be used as IS NULL or IS NOT NULL, since NULL is not a value. This should be what you are looking for ``` SELECT * FROM tbl1 INNER JOIN tbl2 ON tbl1.id = tbl2.id WHERE (@fromdate IS NOT NULL AND tbl1.fromDate = @fromDate) OR (@fromdate IS NULL AND tbl1.date = @resDate) ```
One option might be to use dynamic query and build only the where clause based on your need. ``` DECLARE @sql nvarchar(max) = '<YOUR SELECT & JOIN STATEMENT>' ``` then construct your where clause based on your options, ``` if(<CONDITION1>) BEGIN SET @sql = @sql + '<WHERE CLAUSE FOR CONDITION1>' END if(<CONDITION...
how to avoid repeating multiple selects and inner joins and apply the where clause when its necessary?
[ "", "sql", "sql-server", "" ]
I have tried the different solutions that found on this site when it comes to update or insert using SQL code, I got the update working but can't implement a working insert if the rows doesn't exists, the (update) code that is working looks like this, any help on how to make it insert also would be nice since I'm an \*...
If you have SQL Server 2008 or later, you can make use of the MERGE statement. The following Microsoft TechNet article describes the merge statement pretty well: <https://technet.microsoft.com/en-us/library/bb522522(v=sql.105).aspx> Your query should look something like this: ``` BULK INSERT #tmp_x FROM 'path\to\...
In Sql server, you can do both insert and update in the same statement, called [`MERGE`](https://msdn.microsoft.com/en-us/library/bb510625.aspx) ``` MERGE TTT AS target USING #tmp_x AS source ON (target.Artikelnummer = source.Artikelnummer ) WHEN MATCHED THEN UPDATE SET [Artikelbenämning] = source.[Artikelbenämn...
SQL UPDATE or INSERT
[ "", "sql", "sql-server", "insert", "" ]
I've got two columns in the same table for my users: `name-displayed` and `short-name`. `name-displayed` is populated with the full name of the user, for example "John Doe". In `short-name`, there is the short value, e.g. "john-doe" (essentially de-capitalized and hyphenated). How would I amend the data in `short-nam...
You need to use the `Lower` and `Replace` functions for this. See: [Lower](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_lower) and [Replace](http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace) in the docs. ``` Update <table_name> set `short-name` = REPLACE(LOWER...
You could use triggers: [Triggers](https://www.google.com.br/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwiopdnT173MAhUFGZAKHZW2DVAQFggnMAA&url=https%3A%2F%2Fdev.mysql.com%2Fdoc%2Frefman%2F5.5%2Fen%2Ftrigger-syntax.html&usg=AFQjCNHj2JF0L2PSERatEbgVdbqVEFy1iQ&sig2=BboKED4pgK-H_zEVjCGKBA&bvm=bv.1210...
MySQL: Modify column based on column values in same table
[ "", "mysql", "sql", "multiple-columns", "" ]
``` column name data type wp_stime DATE ``` QUERY: ``` select wp_stime from workpaths; ``` OUTPUT: ``` 29-FEB-12 29-FEB-12 24-FEB-12 24-FEB-12 31-OCT-11 12-DEC-11 12-JAN-11 19-OCT-11 19-OCT-11 11-AUG-11 19-OCT-11 21-NOV-11 28-JUL-11 02-AUG-11 01-MAR-12 01-MAR-12 01-MAR-12 01-MAR-12 01-MAR-12 01-MAR-12 01...
``` select * from workpaths where to_char(wp_stime,'hh24') between 9 and 16; ``` Should help. Oracle will extract the hour part from your date field as string, and on seeing that you are comparing with numbers would implicitly convert it to number. Thus you can compare between hours. Effectively, this query gives date...
trunc(wp\_stime) will return the same date, with the time portion truncated down to 00:00:00. Then wp\_stime - trunc(wp\_stime) will return the "fractional part" (the time portion of wp\_stime). This is expressed as a number, in days. You want this fractional part to be between 9 and 17 hours, or 9/24 and 17/24 days. ...
oracle database: select between certain time of the day
[ "", "sql", "oracle", "" ]
I have following columns in my table: ``` name | columnA | columnB ``` And I am trying to invoke the following query: ``` SELECT name, columnA + columnB AS price FROM house WHERE NOT (columnA IS NULL OR columnB IS NULL) GROUP BY name ORDER BY price ``` Which throws me: house.columnA needs to be in GROUP BY clause....
There are two options: Option 1 - the group by is not needed. This will happen in case there is a single row for each name, in this case: ``` SELECT name,columnA+columnB as price FROM house WHERE columnA is not null AND columnB is not null ORDER BY price ``` Option 2 - the group by is needed, and that means you ha...
i might be missunderstanding you, but i think what you need is a basic sql query without a group. also sum is a function that lets you sum values from different rows. creating the sum of values from the same row is trival. this is how the aggregate function sum could be used to calculate the price for all houses per s...
Issue with SUM of columns and group by
[ "", "sql", "postgresql", "" ]
I have a date in a column like this (`2016-06-01 21:50:00.000`) - `YYYY-MM-DD HH:MM:SS` I am trying to convert it to like this --> (`01/06/2016 21:50:00.000`) `DD-MM-YYYY HH:MM:SS` I've tried the following; ``` SELECT CONVERT(VARCHAR(30), CONVERT(DATETIME, MYDATECOLUMN, 101), 103) FROM MYTABLE ``` **Time part is mi...
try below code ``` select CONVERT(VARCHAR(10), MYDATECOLUMN, 103) + ' ' + convert(VARCHAR(8), MYDATECOLUMN, 14) FROM MYTABLE ``` IF you want to show millisecond also change varchar size from 8 to 12 in second part ``` select CONVERT(VARCHAR(10), MYDATECOLUMN, 103) + ' ' + convert(VARCHAR(12), MYDATECOLUMN, 14) ...
You can use `103` for the date part and then `CAST` the date\_column to `TIME` for getting the time part. **QUERY** ``` SELECT CONVERT(VARCHAR(25), GETDATE(), 103) + ' ' + CAST(CAST(GETDATE() AS TIME) AS VARCHAR(20)); ``` **Result** ``` 02/05/2016 12:43:05.9930000 ``` Or if you want to remove the millisecon...
Time part is missing when using convert
[ "", "sql", "sql-server", "t-sql", "datetime", "" ]
I have been trying to get a sub query to work but I'm thinking it needs to be join instead but I'm new to databases and having a hard time wrapping my head around just how it works. I need to collect a rows from userprofile based on three columns in connect, what I have that doesn't work is this. ``` SELECT * FROM us...
It can be done either via a `join` or a sub-query. Typically with MySQL joins are more efficient because in many cases MySQL is unable to use indexes with sub-queries. So, in your case the query with a join would be: ``` SELECT u.* FROM userprofile u JOIN connect c ON (u.user_id = c.user_id OR u.user_id = c.co...
I think you are with two problems. One of them is the two colmumns thing. The other one is a cartesian product. Try this: ``` SELECT * FROM userprofile up WHERE up.user_id IN (SELECT connect.user_id FROM connect WHERE connect.connect_to_id = '1' UNION ALL S...
MYSQL Sub Query with two columns
[ "", "mysql", "sql", "" ]
I have a table say, ``` column1 column2 a apple a ball a boy b apple b eagle b orange c bat c ball c cork ``` Now I would like to fetch column1 based on the rows that doesn't contain 'apple' and also ignore values in column1 if any of the rows have 'apple' in it. So in the table above only 'C' must ...
Assuming that `column1` is `NOT NULL` you could use: ``` SELECT DISTINCT t.column1 FROM table_name t WHERE t.column1 NOT IN (SELECT column1 FROM table_name WHERE column2 = 'apple'); ``` `LiveDemo` To get all columns and rows change `DISTINCT t.column1` to `*`.
You could use `DISTINCT` with `NOT IN` in following: **QUERY 1 using NOT IN** ``` select distinct col1 from t where col1 not in (select col1 from t where col2 = 'Apple') ``` **QUERY 2 using NOT EXISTS** As per @jarlh comment you could use `NOT EXISTS` in following: ``` select distinct col1 from #t t1 where not exi...
Select statement for Oracle SQL
[ "", "sql", "oracle", "select", "" ]
I am trying to get the minimum price per travel and know which travel-details correspond to that minimum price per travel. For this I have tried all kind of variations with subqueries, joins etc. but since there is not 1 primary key I cannot figure it out. What I'm trying to achieve is get the travel with the lowest ...
You can use `IN()` to do this: ``` SELECT * FROM travel_details t WHERE (t.travel_id,t.price) IN(SELECT s.travel_id,min(s.price) FROM travel_details s GROUP BY s.travel_id) GROUP BY t.travel_id; // this last group-by is to filter doubles when there are mult...
``` Select a.travel_id, a.persons, a.days, a.price from travel_details a JOIN (Select travel_id,MIN(Price) as p from travel_details group by travel_id) b on b.travel_id=a.travel_id and b.p=a.price ``` The above query uses self join. Derived table b will contain travel\_id along with min price.
Find minimum value AND include correct column-values
[ "", "mysql", "sql", "group-by", "min", "" ]
let's say i have this query: ``` SELECT COUNT(datum) FROM unique_ip WHERE (datum>='2016-02-01' AND datum<='2016-02-29') ``` I want to do a WHERE LIKE so only the month has to be specific like 01, 02 etc. So my query is only looking for this: \_\_\_\_-02-\_\_ . How can i use WHERE LIKE in this case? This is my Databa...
You can use the `MONTH()` function or something like `SELECT COUNT(datum) FROM unique_ip WHERE datum LIKE '%-02-%';`.
Use [MONTH()](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_month) function. For your query. ``` $month1 = '02'; $month2 = '02'; SELECT COUNT(datum) FROM unique_ip WHERE (MONTH(datum)>='$month1' AND MONTH(datum)<='$month2') ```
Mysql only WHERE LIKE on month
[ "", "sql", "" ]
I'm having difficulty finding a solution to this problem, as searching for merging SQL columns or adding columns from table gives a wide variety of results I don't want. It's much easier for me to illustrate with an example. I have two tables: **Table 1** ``` ColA ColB ColC 0 A AL 1 B DZ ``` **Tab...
If you want to keep duplicate rows you could use `UNION ALL` and if you want to remove duplicate rows from result set you could use `UNION` in following: ``` SELECT ColA, ColB, ColC FROM Table1 UNION ALL SELECT ColA, ColB, ColC FROM Table2 ``` *Note that `UNION ALL` working faster than `UNION`*
``` select ColA, ColB, ColC from table1 union select ColA, ColB, ColC from table2 ```
Merging columns from identical tables in SQL
[ "", "sql", "select", "" ]
I have a table of adverts. These adverts have `start` and `end` columns, which are both of the `DATETIME` type. I need to select ones that are going to start in the next 24 hours, and, separately, ones that are going to end in the next 24 hours. I wrote the query `select * from slides where enabled = 1 and start <= NO...
So, use two comparisons: ``` select s.* from slides s where s.enabled = 1 and s.start <= NOW() + interval 24 hour and s.start >= NOW(); ```
This works in oracle you can modify it according the DB you are using ``` select * from slides where enabled = 1 and start between sysdate and sysdate+1 ``` Here sysdate returns current date and time, adding 1 to it returns date and time 24 hours from now.
Selecting rows with timestamps set to the future
[ "", "mysql", "sql", "" ]
I want my MySql Column 'Time' to be update as Column 'End\_Time' **Minus** Column 'Start\_Time' Note: End\_Time & Start\_Time are in DATETIME format.... Thanks
Try this method, ``` SELECT SEC_TO_TIME(TIMESTAMPDIFF(second,Start_Time,End_Time)) --include sec or SELECT SEC_TO_TIME(TIMESTAMPDIFF(minute,Start_Time,End_Time)*60) --diff in minute eg SELECT SEC_TO_TIME(TIMESTAMPDIFF(minute,'2016-05-04 10:00:00','2016-05-04 11:29:00')*60) ``` Here `TIMESTAMPDIFF(minute` will retur...
Use Datediff function in mysql [See here for DATEDIFF](http://www.w3schools.com/sql/func_datediff_mysql.asp)
set column values equals to columnB minus columnA
[ "", "mysql", "sql", "" ]
I have a table like: ``` Name Size -------------------------------------- backup_20160426000000.comp.trn 1 backup_20160426001000.comp.trn 2 backup_20160426002000.comp.trn 4 (..) backup_20160426230000.comp.trn 4 backup_20160426231000.comp.trn 5 ``` I need to be able to GROUP the tex...
Since all the strings have the same format, you could just take them appart and reconstruct them using `substring`, as you have partially done: ``` SELECT SUBSTRING(name, 1, 15) + '0000.comp.trn', SUM(size) FROM dbo.CLName GROUP BY SUBSTRING(name, 1, 15) ```
Use `SUBSTRING` function to get the hour. ``` SELECT MIN(Name) AS Name, SUM(Size) AS Size_Sum FROM TblBackup GROUP BY SUBSTRING(Name, 16, 2) ``` Output Result: ``` Name Size_Sum -------------------------------------------- backup_20160426000000.comp.trn 7 backup_2016042623000...
SQL Server : grouping on partial text matching
[ "", "sql", "sql-server", "t-sql", "select", "group-by", "" ]
I have a table of UserIds and rolenames. For example: ``` UserId Rolename 1 Admin 1 Editor 1 Other 2 Admin 3 Other ``` I want to return a single row per user containing `UserId, IsAdmin, IsEditor`, where the latter two columns are booleans representing whether or not the user has the "...
users : ``` UserId UserName 1 amir 2 john 3 sara ``` user roles : ``` UserId RoleName 1 Admin 1 Editor 2 Editor ``` query : ``` select UserId , (select count(UserRoles.UserId) from userRoles where userRoles.UserId=users.Us...
One possible solution: ``` SELECT UserId, CASE WHEN EXISTS (SELECT * FROM #UserRoles A WHERE A.UserId = UR.UserId AND A.Rolename = 'Admin') THEN 'True' ELSE 'False' END AS IsAdmin, CASE WHEN EXISTS (SELECT * FROM #UserRoles E WHERE E.UserId = UR.UserId AND E.Rolename = 'Editor') THEN 'True' ELSE 'False' EN...
How to return a single row aggregating data in multiple rows in SQL
[ "", "sql", "ibm-midrange", "" ]
Let's say I have a `users` table with two column, `id` and `referer_id` [![enter image description here](https://i.stack.imgur.com/DReth.png)](https://i.stack.imgur.com/DReth.png) If the user was refered by someone else, his referrer will be in `referer_id`. If he signed up by himself then the `referer_id` will be NU...
I don't like this, I think there's a more elegant solution out there, but it works and may help you find that better solution. ``` select t1.id, ifnull(t3.ct, 0) from temp t1 left join (select t2.referer_id, count(t2.referer_id) as ct from temp t2 group by t2...
Even though I can't explain what reason caused this issue, I figured it out with another solution, like this;) ``` SELECT `referer_id`, if(`referer_id` is null, @num := @num + 1, count(`referer_id`)) as referer_id_cnt FROM `users`, (select @num := 0) tmp GROUP BY `referer_id` ``` Hmm, what I've wrote above is ...
MySQL Select return wrong NULL value with COUNT
[ "", "mysql", "sql", "" ]
These are my tables: o, p and v corresponding to order, person and village v corresponds to village ``` vk | vname 1 | v1 2 | v2 3 | v3 ``` p corresponds to person in the village. A and B live in V1. C lives in V2. ``` pk | pname | vk 1 | A | 1 2 | B | 1 3 | C | 2 ``` o corresponds to ...
Use left join and inner join ``` SELECT v.vname, count(ok)/count(distinct o.pk) AS avg FROM v left join o on o.pk = p.pk inner join p on p.vk = v.vk group v.vname ```
Try the `LEFT JOIN` instead of `archaic comma join` ``` SELECT v.vname, NULLIF(count(ok)/count(distinct o.pk),0) AS avg FROM v LEFT JOIN p ON p.vk = v.vk LEFT JOIN o ON o.pk = p.pk GROUP BY v.vname ```
Query automatically excluding records with no entries
[ "", "mysql", "sql", "" ]
I'm having an issue where I am running a script against a database to get the average difference between multiple VARCHARs that need to be converted to DateTimes, and then take the average between all the results. My code is: ``` SELECT YEAR(b.DateAcknow),AVG(datediff(dd,convert(datetime,b.DateAssign), convert(dateti...
You are filtering by DateResolv and group by DateAcknow. Filter and group by the same Field and NULL and values outside of the Range should disappear.
You'll probably want to take away the aggregate part and just run: ``` SELECT YEAR(b.DateAcknow) , convert(datetime,b.DateAssign) AS DateAssignDateTime , convert(datetime,b.DateResolv) AS DateResolveDateTime , datediff(dd,convert(datetime,b.DateAssign), convert(datetime,b.DateResolv)) AS AssignResolveDayDiff , convert...
How do I calculate averages of dates formatted as VARCHAR from multiple rows?
[ "", "sql", "datetime", "varchar", "datediff", "" ]
From what I have read about triggers and how they work, I thought that this trigger would insert data into the relations related to my table phonenumber after I insert values into it. I'm using dbms\_random to create a random 5 digit usageID not already in the usage table (or atleast that's what I had thought it would ...
Your trigger is based on an insert on table `phoneNumber` and the error "No Data Found" is thrown when a SELECT INTO is used and it doesnt find any information to insert. So the problem must be this statement. ``` select acctID, primaryNumber into acctNum, primNum from account A where A.primaryNumber = :new.primaryNu...
I show you here what will happen when dbms\_random gives a value (NEWusageID\_new), which exists in the usage: ``` DECLARE i NUMBER; BEGIN SELECT 15 INTO i FROM DUAL MINUS SELECT 15 FROM DUAL; END; ORA-01403: no data found ORA-06512: in line 4 ``` Use a sequence instead.
Why doesn't this trigger work properly?
[ "", "sql", "oracle", "plsql", "triggers", "oracle-sqldeveloper", "" ]
I'm currently using the following SQL query which is returning 25 rows. How can I modify it to ignore the first row: ``` SELECT fiscal_year, SUM(total_sales) as sum_of_year, AVG(SUM(total_sales)) OVER () as avg_sum FROM sales_report GROUP BY fiscal_year ORDER BY fiscal_year ASC ``` I'm using SQL Server 2008. Tha...
You can use `EXCEPT` in SQL Server 2008. ``` SELECT fiscal_year, SUM(total_sales) as sum_of_year, AVG(SUM(total_sales)) OVER () as avg_sum FROM sales_report GROUP BY fiscal_year EXCEPT SELECT TOP 1 fiscal_year, SUM(total_sales) as sum_of_year, AVG(SUM(total_sales)) OVER () as avg_sum FROM sales_report GROUP BY...
assuming this is exactly how you'd query it, then: `SELECT fiscal_year, SUM(total_sales) as sum_of_year, AVG(SUM(total_sales)) OVER () as avg_sum FROM sales_report WHERE fiscal year <> (SELECT MIN(Fiscal_year) FROM sales_report)) GROUP BY fiscal_year ORDER BY fiscal_year ASC` And then you can remove the "order by". ...
Select all rows and ignore the first row
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "" ]
Objective: `Remove all` entries `where` `LastLogin` is `null` `AND` `RegDate` is older than 30 seconds. I'm trying to use transact SQL to remove an entry from table 'ONE' ``` SELECT * FROM dbo.ONE WHERE LastLogin == Null AND RegDate is older than DATETIME.NOW by 30 seconds; ``` I hope the question makes sense. So h...
As @Alex K. pointed out check for null and using datediff ``` select * from dbo.ONE where LastLogin is NULL and datediff(ss,regdate,GetDate())<30 ```
Im not 100% sure about the older part you mean `<` or `>` . But should be something like this. ``` DELETE FROM dbo.ONE WHERE LastLogin IS NULL AND RegDate < DATEADD(ss, -30, getdate()); ``` getdate() is current time
How do I Remove an entry which is more than 30 seconds old And has null value
[ "", "sql", "t-sql", "datetime", "" ]
I have a table that holds a list of classes available at a school. Each class can have a number of sessions. And each class can have pupils assigned to it. What I need to do is get a count of all sessions for each class, as well as the number of students attending the class. I have done the first bit, but if I join to...
You have two independent dimensions for each class. You need to aggregat them separately: ``` SELECT c.ClassName, cs.Sessions, cp.Pupils FROM @Class c INNER JOIN (SELECT ClassId, COUNT(*) as sessions FROM @ClassSession cs GROUP BY ClassId ) cs ON cs.ClassID = c.ClassID INNER JOIN (SELE...
Another method is to use `CROSS APPLY` to get the count of pupils: ``` SELECT ClassName, COUNT(*) AS Sessions, cp.NumberOfPupils FROM @Class c INNER JOIN @ClassSession cs ON cs.ClassID = c.ClassID CROSS APPLY ( SELECT COUNT(*) AS NumberOfPupils FROM @ClassPupil WHERE ClassID = c.ClassID ) ...
COUNT of different tables in GROUP
[ "", "sql", "sql-server", "sql-server-2014", "" ]
For example, I have a time format: 1000 how do I convert into MySQL Time() 10:00:00 It can also be more complex, since some numbers are 3 digits long, for example: 900 into MySQL Time() 09:00:00 Let me know if this needs more explaining.
Use CONVERT() -- (<http://dev.mysql.com/doc/refman/5.7/en/charset-convert.html>) You'll have to pad it with zeros to show CONVERT() that it is in hours and not minutes. **Specific to your example:** ``` > SELECT CONVERT(CONCAT('1000','00'), TIME) AS time1; time1 10:00:00 ``` or ``` > SELECT CONVERT(CONCAT(`fieldna...
You just want to use [str\_to\_date()](https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date) cast your into to a char so its a string and pad it with lpad to keep a leading 0 :) ``` SELECT STR_TO_DATE(LPAD(CAST(my_col AS CHAR(25)), 4, '0'), '%H') -- or %k ``` or you can just drop...
How to convert int number into time - SQL
[ "", "mysql", "sql", "" ]
I have 2 tables Table1. StudentMaster ``` ROLL CLASS NAME TOTALMARKS STREAMID ---------- ---------- ------------ ---------- ---------- 12345 5 Rohit 75 100 12346 7 Suman 95 101 12347 5 Rajib 41 100 12...
I have finally solved this problem with the simplest way possible (I think) ``` select studentmaster.name,studentmaster.totalmarks highest_marks,stream.name stream from studentmaster,stream where studentmaster.streamid=stream.streamid and totalmarks in(select max(totalmarks) from studentmaster group by streamid); ```
You can use this: ``` SELECT * FROM (SELECT ROW_NUMBER() OVER(PARTITION BY STREAMID ORDER BY TOTALMARKS desc NULLS LAST) AS RANK, StudentMaster.name, stream.name AS stream, totalMarks AS HighestMarks FROM StudentMaster INNER JOIN STREAM USING (streamId)) WHERE ...
Getting Stream wise Highest Marks in SQL
[ "", "sql", "oracle", "greatest-n-per-group", "" ]
My query look like: ``` select * from `games` inner join `prowizja` on `prowizja`.`id_gry` = `games`.`id` where `games`.`status` = 2 and `games`.`winner_user_id` != 49 and `games`.`owner_user_id` = 49 or `games`.`join_user_id` = 49 ``` Important think is **games`.`winner\_user\_id` != 49**. But I result of this ...
You probably have to wrap the last two predicates of the `WHERE` clause in parentheses: ``` select * from `games` inner join `prowizja` on `prowizja`.`id_gry` = `games`.`id` where `games`.`status` = 2 and `games`.`winner_user_id` != 49 and (`games`.`owner_user_id` = 49 or `games`.`join_user_id` = 49) `...
`AND`has precedence over `OR`. Hence your query equals: ``` select * from games inner join prowizja on prowizja.id_gry = games.id where (games.status = 2 and games.winner_user_id <> 49 and games.owner_user_id = 49) or games.join_user_id = 49; ``` where you want it to be ``` select * from games inner join prowizja...
Wrong result of (or where query)
[ "", "mysql", "sql", "" ]
I currently have a complex SQL query which is inserted into a temp table. The query includes an `OUTER APPLY` as not all returned records will apply to the result set. I also need to use the `OUTER APPLY` columns in the `WHERE` clause to filter results but also include the results which do not apply into the `OUTER AP...
You can't compare directly to `NULL` because nothing equates to `NULL` (not even `NULL` itself). That precludes using `IN` here. Instead, just use an `OR` statement: ``` INSERT INTO #temp (X, Y, Z, O1, O2) SELECT X, Y, Z, FROM T1 INNER JOIN T2 ON ... OUTER APPLY (SELECT O1, O2 FROM XYZ…) OATable WHERE OATable...
I think the answer from Tom H adresses the stated question But I think this might be what you are actually looking for ``` SELECT X Y Z, OATable.* FROM T1 INNER JOIN T2, T etc. LEFT JOIN XYZ as OATable on OATable.O1 = 1 ``` In the answer from Tom you would need a literal OATable.O1 IS NULL (from my findi...
Filter OUTER APPLY column in WHERE clause
[ "", "sql", "sql-server", "database", "t-sql", "sql-server-2012", "" ]
I am developing an Oracle database schema visualizer. So, as a first step, I thought, I will first need to get all the schema details (tables and relationships between tables, constraints also maybe). To get that information, what is the SQL command that will return the result? (the `DESCRIBE` command does not return...
I do something similar. I read those things from a SQL Server over OPENQUERY statements directly from Oracle DBs and save results into SQL Server tables to allow analysis of historic comparison schema information and changes. So what you have to do with the resultsets of the following queries is to store them (regular...
You could start with: ``` select DBMS_METADATA.GET_DDL ('TABLE', table_name,user) from user_tables; ``` That will reverse engineer all the DDL that would create the tables. It wouldn't give you current table/column statistics though. Some tools (eg Oracle's Data Modeller / SQL Developer) will allow you to point them...
Oracle : which SQL command to get all details about a table?
[ "", "sql", "oracle", "schema", "" ]
I have 2 tables `Document_type_de` and the other is `document` . `Document` table has all the documents stored but which type of document it is, is defined in `document_type_de`, so i need help with the query which will help me find the count of the documents of each type in the document table. columns under document\...
This'll do it: ``` SELECT Type.[Display Name], COUNT(*) AS [Number of Documents] FROM Document_type_de Type JOIN Document D ON Type.ID = D.documenttypede GROUP BY Type.[Display Name] ORDER BY Type.[Display Name] ```
That query will give you the count of all the documents grouped by documents\_type\_id. Dunno about you tables primarys and foreign keys names, just replace it. ``` SELECT count(documents_id) FROM document d INNER JOIN Document_type_de dtd dtd.document_id = d.document_id GROUP BY d.documents_type_id ``` Regards.
count using inner join from 2 tables
[ "", "sql", "" ]
Access Query that I need to convert to work under SQL Server: ``` TRANSFORM Sum([T_Leads]![OrderType]='New Order')-1 & " / " & Sum([T_Leads]![OrderType]='Change Order')-1 AS [New / Change] SELECT Employees.EmployeeName as Name, Count(T_Leads.OrderType) AS Total FROM Employees INNER JOIN T_Leads ON Employees.Employ...
``` IF OBJECT_ID('tmpEmployees_Test', 'U') IS NOT NULL DROP TABLE tmpEmployees_Test; CREATE TABLE tmpEmployees_Test (EmployeeID INT, EmployeeName VARCHAR(255)); INSERT tmpEmployees_Test (EmployeeID, EmployeeName) VALUES (1, 'Doe, Jane'), (2, 'Doe, John'), (3, 'Guy, Some'); IF OBJECT_ID('tmpOrders_Test', 'U') IS NOT N...
You'd need to dynamically produce your pivot columns then do case statements for each of them. The following is an example of how you could do it: ``` IF OBJECT_ID('tmpEmployees_Test', 'U') IS NOT NULL DROP TABLE tmpEmployees_Test; CREATE TABLE tmpEmployees_Test (EmployeeID INT, EmployeeName VARCHAR(255)); INSERT tmpE...
Convert Access Crosstab/PIVOT query to T-SQL
[ "", "sql", "sql-server", "t-sql", "ms-access", "" ]
I have the following Table. ``` STAFF STAFFNO STAFFNAME DESIGNATI SALARY DEPTNO ---------- ---------- --------- ---------- ---------- 1000 Rajesh Manager 35000 1 1001 Manoj Caretaker 7420.35 1 1002 Swati HR 22...
You need create a sub query or perform a `JOIN`. With a `JOIN` first you need to know what department has more that 5 employees. ``` SELECT DEPTNO FROM STAFF GROUP BY DEPTNO HAVING COUNT(*) >= 5 ``` Now you join both result ``` SELECT S.* FROM STAFF S JOIN ( SELECT DEPTNO FROM STAFF GROUP BY D...
It should be like this ``` SELECT * FROM STAFF WHERE DEPTNO IN (SELECT DEPTNO FROM STAFF GROUP BY DEPTNO HAVING COUNT(*)>4) ```
SQL Query to Retrieve the details of those employees who works in a department having head count more than 5
[ "", "sql", "database", "oracle", "" ]
I'm trying to rewrite some old SQL queries that look particularly awful. I am wondering if there is a more efficient way to prioritize values in a where statement for order of precedence. Basically the table contains multiple email\_code records per user but I want to prioritize based on what records are preferred. In ...
Try: ``` SELECT * FROM ( SELECT e.*, dense_rank() over (PARTITION BY user_id ORDER BY CASE email_code WHEN 'WORK' THEN 1 WHEN 'HOME' THEN 2 WHEN 'ALT1' THEN 3 WHEN 'ALT2' THEN 4 ELSE 5 END ) As priority FRO...
First of all, it shall be better to create a lookup table to hold email types and their priorities. And then you can join this lookup table with your mail table. Finally, it will be ok to use one of Oracle analytic functions ( row\_number, rank, dense\_rank etc ) in order to get the highest priority one.
oracle select based on priority
[ "", "sql", "oracle", "select", "operator-precedence", "" ]
I am having different results on what appears to be the same query. I am very confused on why the total differs from the queries. Hopefully someone has an explanation on this issue and maybe say which should be the correct total. Thank you ``` select sum(tm_hours) FROM bhds_timecard WHERE (tm_notes = 'Session' OR ...
If you understand why 5 + 3 \* 2 = 11 then this will help understand the source of your problem. Some people may mistakenly think the above calculation should give you 16 because they are unaware of the order of operations. Multiplication takes precedence over addition so it is done first. Likewise, AND has a higher p...
Second query must be like that: ``` SELECT SUM(tm_hours) FROM bhds_timecard WHERE (tm_date BETWEEN '2016-04-01' AND '2016-04-30') AND (tm_notes = 'Session' OR tm_notes = 'Intake' OR tm_notes = 'OT' OR tm_notes = 'PT' OR tm_notes = 'Speech') ``` You lose the `(` bracket for second group of conditions
Difference on sum totals on mysql query
[ "", "mysql", "sql", "sum", "" ]
I am writing a query like this ``` SELECT * FROM table WHERE id IN (thousands of ids) ``` but this won't work because the limit of values for the `WHERE IN` is 128 on our version of SQL Server. Is there a way to do this using a sub-query with a join, or maybe a temp table? Any help is appreciated!
You can use [**`VALUES`**](https://msdn.microsoft.com/en-us/library/dd776382.aspx) in order to construct an in-line table containing all the values to be considered and then `JOIN` to this table: ``` SELECT t1.* FROM table AS t1 INNER JOIN (VALUES (10), (20), (12), ... ) AS t2(id) ON t1.id = t2.id ```
Place them in temp table and ``` SELECT * FROM table WHERE id IN (SELECT id from #Table_of_thousands_of_ids) ```
SQL Server : how to work around WHERE IN limit of 128 values
[ "", "sql", "sql-server", "" ]
``` student table teacher table sports table parents table --------- -------------- ------------ --------------- id name id name id name id stud_id fathername mothername ------------ ------------ ------------ ----------------------------------------- 1 ...
You can simply use where clause : ``` select S.name, T.name, SS.name, P.fathername, P.mothername from student S, teacher T, sports SS, parents P,student_teacher ST, student_sports SSP where S.id = ST.stud_id and T.id = ST.teacher_id and S.id = SSP.stud_id and SS.id = SSP.sports_id and S.id = P.stud_id ```
Here is the solution : ``` select st.name as Student, t.name as teacher, sp.name as sports, p.fathername,p.mothername from student st,teacher t,sports sp,parents p,student_teacher s_t,student_sports s_s where s_t.stud_id=st.id and s_t.teacher_id=t.id and p.stud_id=st.id and s_s.stud_id=st.id; ```
How to retrieve the student information from the table?
[ "", "mysql", "sql", "join", "" ]
I'm studying for my Database System exam tomorrow, and I'm working on an SQL question. This question is the only one from the paper that doesn't have an answer, but here's the question: --- We use the following schema: * *Professor*(name, office, dept, age) (age is key) * *Course*(cno, title, dept) (cno stands for c...
With aggregate function you shoud use having ``` SELECT "Yes" FROM dbsProfs HAVING MAX(dbsProfs.age) - MIN(dbsProfs.age) <= 5 ```
``` WITH dbsProfs AS ( SELECT MIN(P.age) as min_age,MAX(P.age) as max_age FROM Professor P, Enroll E, Course C WHERE P.name = E.inst_name AND C.cno = E.cno AND C.title = "Database Systems" AND E.enrollment BETWEEN 2000 and 2009 ) SELECT CASE WHEN min_age<max_age THEN "Yes" END FROM dbsProfs ```
SQL Query outputting "yes"
[ "", "mysql", "sql", "view", "" ]
I am trying to generate a report on a sql server database in asp.net and I am getting the results of some columns as a product of two columns. Here is the code ``` comm.CommandText = "SELECT Count(Courses.CourseID) AS CourseCount, Count(Students.StudentID) AS StudentCount, Schools.Name, Schools.StartDate, Schools.S...
Changing your code from using a count of all rows, to a count of distinct values only, should return the results you expect ``` comm.CommandText = "SELECT Count(DISTINCT Courses.CourseID) AS CourseCount, Count(DISTINCT Students.StudentID) AS StudentCount, Schools.Name, Schools.StartDate, Schools.SchoolFees " + ...
As stated above, it is how you are using the COUNT (), You are asking it to count all, which is why it returns so many. Use count on just the two values you want counted.
Sql Joins on multiple table returning product of two columns
[ "", "sql", "asp.net", "sql-server", "database", "" ]
I have following list of `Amount (float)` in my table. ``` Amount 123 123.1 123.0123 123.789456 ``` How can i get the number of digits after the decimal point. **Duplicate ?:** I have checked already existing posts, but there is no correct way to handle the **`float`** numbers **`with or without decimal part`**. Re...
I found some simple script (relatively to me) to handle this. ``` ISNULL(NULLIF(CHARINDEX('.',REVERSE(CONVERT(VARCHAR(50), Amount, 128))),0) - 1,0) ``` Here the `ISNULL(NULLIF` is only to handle the float without decimal part. If there is no values without decimal part, then it is very simple ``` CHARINDEX('.',REVER...
You can do It in following: **QUERY** ``` SELECT Amount, CASE WHEN FLOOR(Amount) <> CEILING(Amount) THEN LEN(CONVERT(INT,CONVERT(FLOAT,REVERSE(CONVERT(VARCHAR(50), Amount, 128))))) ELSE 0 END AS Result FROM YourTable ``` **OUPUT** ``` Amount Result 123 0 123,1 1 123,0123 4 123,789456 ...
Get the number of digits after the decimal point of a float (with or without decimal part)
[ "", "sql", "sql-server", "sql-server-2008", "" ]
Here's where I am: * `TABLE1.ITM_CD` is VARCHAR2 datatype * `TABLE2.ITM_CD` is NUMBER datatype * Executing `left join TABLE2 on TABLE1.ITM_CD = TABLE2.ITM_CD` yields **ORA-01722: invalid number** error * Executing `left join TABLE2 on to_number(TABLE1.ITM_CD) = TABLE2.ITM_CD` also yields **ORA-01722: invalid number** ...
You can convert the `TABLE1.ITM_CD` to a number after you strip any leading zeros and filter out the "MIXED" values: ``` select A.ITM_CD ,B.COST ,B.SIZE ,B.DESCRIPTION ,A.HOLD_REASON from ( SELECT * FROM TABLE1 WHERE ITM_CD <> 'MIXED' ) a left join TABLE2 b on TO_NUMBER( LTRIM( a.I...
This is a SQL (and really a database) problem, not PL/SQL. You will need to fix this - fight your bosses if you have to. Item code must be a Primary Key in one of your two tables, and a Foreign Key in the other table, pointing to the PK. Or perhaps Item code is PK in another table which you didn't show us, and Item cod...
PL/SQL Developer: joining VARCHAR2 to NUMBER?
[ "", "sql", "oracle", "" ]
I created the following tables: ``` create table people ( ID varchar(9), name varchar(20), CONSTRAINT pk_ID PRIMARY KEY (ID) ); create table cars ( license_plate varchar(9), ID varchar(9), CONSTRAINT pk_ID PRIMARY KEY (license_pla...
``` select name from people where ID not in ( select distinct c.ID from accidents as a inner join cars as c on a.license_plate = c.license_plate ) ``` Explanation = the sub query will join the cars and accidents, will give you the ID's of all cars who had accidents. On this you can run `not in` query on t...
I need two subquery ``` select id from people where id not it (select id form cars where licens_plate not in (select distintc license_plate from accidents)) ```
how to get the ID card in MYSQL?
[ "", "mysql", "sql", "" ]
I have three tables Table1 ``` userid mobile 1 123456789 2 321654987 3 987456321 ``` Table2 ``` revid userid revdes mobile 1 2 ASD 123456789 2 2 DSA 123456348 3 1 QWE 963258124 ``` Table3 ``` revid revloc 1 asdf 3 dsaq ``` I wan...
You can achieve what you want using a series of left joins. The tricky part with your query was knowing to join `Table1` and `Table2` using the mobile number, rather than the user id. ``` SELECT t2.userid, t2.revid, t2.revdes, t2.mobile, t3.revloc, t1.mobile IS NOT NULL AS inTable1 FROM Table2 t2 LEFT JOIN Table1 ...
You could use a `left join` and just check if the resulting column is `null` or not: ``` SELECT t2.userid, t2.revid, t2.revdes, t2.mobile, t3.revloc, t1.mobile IS NOT NULL AS inTable1 FROM table2 t2 JOIN table3 t3 ON t2.revid = t3.revid LEFT JOIN table1 t1 ON t2.mobile = t1.mobile ```
MySQL three table join
[ "", "mysql", "sql", "select", "join", "" ]
I thought this would have been an easy google search but couldn't find any solutions. Is there a way to use the like and between together in a query? Example ``` REASON_CODES A00 VMC B10 A00 RTD B19 . . . A99 RNT B40 ``` I am trying to write a query like: ``` Select count(*) from table_1 where REASON_CODES like be...
You can use substring ``` Select count(*) from table_1 where substr(reason_codes, 1,3) between 'A10' and 'A25'; ```
If you're just trying to match the beginning of the `REASON_CODE` strings, you can do: ``` SELECT COUNT(*) FROM table_1 WHERE REASON_CODE >= 'A10' AND REASON_CODE < 'A26' ``` This is equivalent to scaisEdge's answer, but it can take advantage of an index on the `REASON_CODE` column, which cannot be used if you first ...
Oracle like and between used together
[ "", "sql", "oracle", "sql-like", "" ]
I have an SQL table with 4 columns. The fourth column is FullName. I want this column to autofill itself from the results of 2nd and 3rd Column. ie.Firstname and Middlename. I have tried this code ``` cn.Open() Dim query As String query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1....
The section CONCATINATE will be like the following: ``` "CONCATE('" & Textbox2.text &"',',','" & Textbox3.Text & "'))" ``` But i wont tell you to use like this, since it may a worst suggestion. I prefer you to use parameters as well to avoid injection and specifying the types. Example: ``` Dim query = "Insert into ...
Before query first store two textbox value in one variable ``` cn.Open() Dim query As String Dim fullname As String fullname = TextBox1.text + "" + TextBox2.text query = "Insert into Details(Adm,FirstName,MiddleName,FullName ) VALUES ('" & TextBox1.Text & "' , '" & TextBox2.Text & "', '" & TextBox3.Text & " ', '" & f...
Combining two Columns
[ "", "sql", "vb.net", "" ]
I'm at my first question on stackexchange, as i have a few days since I struggle on this matter: I want to make a complex query(PLSQL) on a table that has **col1,col2,col3,col4,col5** having values like (names: which are split- one part per column) ``` +------+--------+--------+--------+------+ | ID | Col1 | Col...
If you're on 11g or higher, you can unpivot your columns into rows; this is using a CTE to provide your sample data: ``` with t (id, col1, col2, col3, col4, col5) as ( select 1, 'Andrew', 'Joan', 'Bach', 'Mike', null from dual union all select 2, 'Mark', 'Andrew', 'Livy', null, null from dual union all select 3,...
You can do it using Oracle's collections (which should work in 10g or later) **Oracle Setup**: ``` CREATE TABLE TABLE_NAME( ID, Col1, Col2, Col3, Col4 ) AS SELECT 1, 'Andrew', 'Joan', 'Bach', 'Mike' FROM DUAL UNION ALL SELECT 2, 'Mark', 'Andrew', 'Livy', NULL FROM DUAL UNION ALL SELECT 3, 'Joan', 'Arch', ...
How to make a query on multiple columns without writting all possible permutations?
[ "", "sql", "oracle", "" ]
I have a database with a **Datetime** column containing intervals of +/- 30 seconds and a **Value** column containing random numbers between 10 and 100. My table looks like this: ``` datetime value ---------------------------- 2016-05-04 20:47:20 12 2016-05-04 20:47:40 44 2016-05-04 20:48:30 56 ...
Sorry if I'm repeating another answer. I'll delete if I am.. ``` SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(datetime)/300)*300) x , MIN(value) min_value , MAX(value) max_value FROM my_table GROUP BY x; ```
Use various date partition functions inside a GROUP BY. Code: ``` SELECT from_unixtime(300 * round(unix_timestamp(r.datetime)/300)) AS 5datetime, MAX(r.value) AS max_value, MIN(r.value) As min_value, (SELECT r.value FROM random_number_minute ra WHERE ra.datetime = r.datetime order by ra.datetime desc LIMIT 1) as fir...
How to group time column into 5 minute intervals and max/min value respectively SQL?
[ "", "mysql", "sql", "database", "select", "" ]
How might I select the following data in an existing table and order by a mix of letters and numbers. Here is the sample... ``` A-1 A-10 A-2 A-3 A-4 A-5 A-6 A-7 A-8 A-9 A-3a A-3b A-3c B-1 B-10 B-11 B-12 B-12a B-12b B-13 B-2 B-3 B-4 B-5 B-6 B-7 B-8 B-9 ```
I place this as a new answer, as it is not really an answer but rather a comparison of different approaches: ### The conclusio: * all approaches scale fairly linear, except XML * XML is fastest with small row count but gets worse with high row count ### Create a test scenario ``` CREATE TABLE #tbl (ID INT IDENTITY,...
The most powerful solution is to create an [SQL CLR function](https://stackoverflow.com/a/10840893/5931028). That's a bit tough, though. Another approach is writing an insert/update trigger that splits the value in the mixed column with TSQL and stores the three parts (character, number, character) in specific helper ...
SQL: Order by substring of mixed letters and numbers
[ "", "sql", "sql-server-2008", "" ]
I want to know what's the best datatype to store these: * `null` * `0` * `/* the length of other numbers is always 7 digits */` * `0000000` * `0000001` * `0000010` * `0000011` * `/* and so on */` * `1111111` I have tested, `INT` works as well. But there is a better *datatype*. Because all my numbers are made of `0` o...
What you are showing are binary numbers * 0000000 = 0 * 0000001 = 2^0 = 1 * 0000010 = 2^1 = 2 * 0000011 = 2^0 + 2^1 = 3 So simply store these numbers in an integer data type (which is internally stored with bits as shown of course). You could use BIGINT for this, as recommended in the docs for bitwise operations (<ht...
As you've said in a comment, the values `01` and `1` should not be treated as equivalent (which rules out binary where they would be), so you could just store as a string. It actually might be more efficient than storing as a byte + offset since that would take up 9 characters, whereas you need a maximum of 7 characte...
Best datatype to store a long number made of 0 and 1
[ "", "mysql", "sql", "sqldatatypes", "" ]
I have 3 tables. * InvoiceOriginal * Invoice * InvoiceHistory the invoice table has a foreign key constraint. Each entry in the invoice table has a corresponding entry in Invoiceoriginal. The invoiceOriginal table stores the original values of the invoice and invoice table stores the values which have been modified ...
You cannot issue a delete statement against more than one table at a time, you need to have individual delete statements for each of the related tables before deleting the parent record(s)
I'm fairly sure you can't delete from multiple tables with a single statement. I would normally delete the child rows first with one statement and then delete the parent record. You may wish to do this inside a transaction if you might need to roll back on failure. Alternatively, you could enable CASCADE ON DELETE on ...
Delete from 2 tables using INNER JOIN
[ "", "sql", "sql-server", "sql-delete", "" ]
I have a table of course : [![enter image description here](https://i.stack.imgur.com/7jdtU.png)](https://i.stack.imgur.com/7jdtU.png) I want to fetch data from searching based on columns Country, university, level, interest and substream. Query which I've tried but not getting better result. ``` select * from edu_...
Try this method, ``` select * from edu_college_desc where country = ISNULL(@country ,country) and university = ISNULL(@university ,university) and leveln = ISNULL(@level ,leveln) and interest = ISNULL(@interest ,interest and substream = ISNULL(@substream,substream) ``` In t...
For each category, check if the parameter is null (not given) or the same as specified: ``` select * from edu_college_desc where (@country is null or country = @country) and (@university is null or university = @university) and etc... ``` And, of course, you can also use MS SQL Server's `ISNULL`, just as in Abdul...
Fetch data from table based on multiple columns from same table
[ "", "sql", "sql-server", "" ]
I have this table: ``` // numbers +---------+------------+ | id | numb | +---------+------------+ | int(11) | bit(10) | +---------+------------+ | 1 | 1001100111 | | 2 | 0111000101 | | 3 | 0001101010 | | 4 | 1111111011 | +---------+------------+ ``` Now I'm trying to get third di...
Although you could use `substr` after converting to `varchar`, a simpler approach for `BIT(...)` data type it to use bit operators. Since according to your comment it is OK to extract 8-th bit from the right, rather than the third bit from the left, this will produce the expected result: ``` select id, (x>>7)&1 from ...
You could convert `BIT` to `VARCHAR` (*or `CHAR`*) and then use `SUBSTR` in following: ``` SELECT SUBSTR(CONVERT(VARCHAR(10),numb), 3, 1) FROM numbers ``` Or using `LEFT` and `RIGHT`: ``` SELECT LEFT(RIGHT(CONVERT(VARCHAR(10),numb),8),1) FROM numbers ```
How to use substr(...) for BIT(...) data type columns?
[ "", "mysql", "sql", "" ]
I have a table which shows Grades and percentages. Now I want to run query on table which fetch Grade between these percentages. Example if a student get 72% I want to show the Grade as `C`. How to get Grade from table? Please refer this table picture: [![enter image description here](https://i.stack.imgur.com/y...
``` Drop Table Grades Drop Table Students Create Table Students (Name Varchar(200), Percentage Numeric(5,2)) Insert Students Values ('John', 0.00) Insert Students Values ('Jane', 38.00) Insert Students Values ('Joe', 45.00) Insert Students Values ('Greg', 50.00) Insert Students Values ('Buck', 55.00) Insert Students V...
`ORDER BY Percentage DESC` with `<=` the percentage in WHERE and `TOP 1 Grade` will given the expected result ``` CREATE TABLE #GradeMaster (Grade VARCHAR(2), Percentage DECIMAL(5,2)) INSERT INTO #GradeMaster SELECT 'A*', 101 UNION SELECT 'A', 85 UNION SELECT 'B', 75 UNION SELECT 'C', 65 UNION SELECT 'D', 55 UNION SE...
How to get numeric range between row value SQL
[ "", "sql", "" ]
This is the SQL statement which I taken from debug mode in VB.Net. ``` SELECT dt_Date as 'Date', s_Time as 'Time', s_For as 'For', s_Categ as 'Category', s_Count as 'Count', s_Remarks as 'Remarks' FROM Entry WHERE (s_ENo = '22' and dt_date BETWEEN '06-05-16' And '27-05-1...
If you are using MS-SQL server than use following instructions. The basic solution is that you have to provide date into either mm/DD/YYYY format or in YYYY-MM-DD date format into ms-sql query. So, before passing date to query convert your date into either mm/DD/YYYY format or in YYYY-MM-DD format.
Instead if string literals, use strongly-typed parameters. In addition to avoiding data type conversion issues on the SQL Server side, parameters: * Avoid the need to format date/time string literals in a particular way * Improve performance by providing execution plan resue * Prevent SQL injection (barring dynamic SQ...
SQL statement error in VB.Net
[ "", "mysql", "sql", "sql-server", "vb.net", "visual-studio", "" ]