Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
In the SQL space (specifically T-SQL, SQL Server 2008), given this list of values: ``` Status Date ------ ----------------------- ACT 2012-01-07 11:51:06.060 ACT 2012-01-07 11:51:07.920 ACT 2012-01-08 04:13:29.140 NOS 2012-01-09 04:29:16.873 ACT 2012-01-21 12:39:37.607 <-- THIS ACT 2012-01-21 12:40:03.840 ACT 2012-05-02 16:27:17.370 GRAD 2012-05-19 13:30:02.503 GRAD 2013-09-03 22:58:48.750 ``` Generated from this query: ``` SELECT Status, Date FROM Account_History WHERE AccountNumber = '1234' ORDER BY Date ``` The status for this particular object started at ACT, then changed to NOS, then back to ACT, then to GRAD. What is the best way to get the minimum date from the latest "group" of records where Status = 'ACT'?
Here is a query that does this, by identifying the groups where the student statuses are the same and then using simple aggregation: ``` select top 1 StudentStatus, min(WhenLastChanged) as WhenLastChanged from (SELECT StudentStatus, WhenLastChanged, (row_number() over (order by "date") - row_number() over (partition by studentstatus order by "date) ) as grp FROM Account_History WHERE AccountNumber = '1234' ) t where StudentStatus = 'ACT' group by StudentStatus, grp order by WhenLastChanged desc; ``` The `row_number()` function assigns sequential numbers within groups of rows based on the `date`. For your data, the two `row_numbers()` and their difference is: ``` Status Date ------ ----------------------- ACT 2012-01-07 11:51:06.060 1 1 0 ACT 2012-01-07 11:51:07.920 2 2 0 ACT 2012-01-08 04:13:29.140 3 3 0 NOS 2012-01-09 04:29:16.873 4 1 3 ACT 2012-01-21 12:39:37.607 5 4 1 ACT 2012-01-21 12:40:03.840 6 5 1 ACT 2012-05-02 16:27:17.370 7 6 1 GRAD 2012-05-19 13:30:02.503 8 1 7 GRAD 2013-09-03 22:58:48.750 9 2 7 ``` Notice the last row is constant for rows that have the same status. The aggregation brings these together and chooses the latest (`top 1 . . . order by date desc`) of the first dates (`min(date)`). EDIT: The query is easy to tweak for multiple account numbers. I probably should have written that way to begin with, except the final selection is trickier. The results from this has the date for each status and account: ``` select StudentStatus, min(WhenLastChanged) as WhenLastChanged from (SELECT StudentStatus, WhenLastChanged, AccountNumber (row_number() over (partition by AccountNumber order by WhenLastChanged) - row_number() over (partition by AccountNumber, studentstatus order by WhenLastChanged) ) as grp FROM Account_History ) t where StudentStatus = 'ACT' group by AccountNumber, StudentStatus, grp order by WhenLastChanged desc; ``` But you can't get the last one per account quite so easily. Another level of subqueries: ``` select AccountNumber, StudentStatus, WhenLastChanged from (select AccountNumber, StudentStatus, min(WhenLastChanged) as WhenLastChanged, row_number() over (partition by AccountNumber, StudentStatus order by min(WhenLastChanged) desc ) as seqnum from (SELECT AccountNumber, StudentStatus, WhenLastChanged, (row_number() over (partition by AccountNumber order by WhenLastChanged) - row_number() over (partition by AccountNumber, studentstatus order by WhenLastChanged) ) as grp FROM Account_History ) t where StudentStatus = 'ACT' group by AccountNumber, StudentStatus, grp ) t where seqnum = 1; ``` This uses aggregation along with the window function `row_number()`. This is assigning sequential numbers to the groups (after aggregation), with the last date for each account getting a value of 1 (`order by min(WhenLastChanged) desc`). The outermost `select` then just chooses that row for each account.
``` SELECT [Status], MIN([Date]) FROM Table_Name WHERE [Status] = (SELECT [Status] FROM Table_Name WHERE [Date] = (SELECT MAX([Date]) FROM Table_Name) ) GROUP BY [Status] ``` Try here `Sql Fiddle`
Find minimum value in groups of rows
[ "", "sql", "sql-server", "t-sql", "group-by", "" ]
I have a temp table with some columns containing numbers. I want to use the columns in the temp table and compare them WITH an IF statement. ``` ... INSERT INTO #tmp EXEC [p_GetComplete] @Car_ID IF Col1 + Col2 = Col3 BEGIN PRINT 'OK' END ELSE BEGIN PRINT 'NO' END ... ```
SQL Is made to operate on SET, so avoid CASE WHEN and IF as long as you can: You can do it this way (recommended): ``` SELECT 'Ok' FROM #tmp WHERE Col1+Col2=Col3 UNION ALL SELECT 'NO' FROM #tmp WHERE NOT (Col1+Col2=Col3) ``` or this way: ``` SELECT CASE WHEN Col1+Col2=Col3 THEN 'Ok' ELSE NO FROM #tmp WHERE ```
You can use case statement, when wanting to insert different value to #tmp table, according to some conditions. Such as on: [SQL Server: CASE WHEN OR THEN ELSE END => the OR is not supported](https://stackoverflow.com/questions/5487892/sql-server-case-when-or-then-else-end-the-or-is-not-supported) If you want searching every record, and do some printing, there is good example on: <http://technet.microsoft.com/en-us/library/ms180152.aspx> Good luck!!!
IF statement from a temp table
[ "", "sql", "sql-server", "" ]
I 've a query that links many tables. So when executes a stored procedure it gives... ``` Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ``` What can I do for this.. May I have to increase the time out of the SQL server. I'm using SQl 2008. Could you please help me to resolve this..
When one transaction holds a lock on a data resource and another transaction requests an incompatible lock on the same resource, the request is blocked and the requester enters a wait state. By default, the blocked request keeps waiting until the blocker releases the interfering lock. To get lock information, including both locks that are currently granted to sessions and locks that sessions are waiting for, query the dynamic management view (DMV) sys.dm\_tran\_locks as: ``` SELECT -- use * to explore other available attributes request_session_id AS spid, resource_type AS restype, resource_database_id AS dbid, DB_NAME(resource_database_id) AS dbname, resource_description AS res, resource_associated_entity_id AS resid, request_mode AS mode, request_status AS status FROM sys.dm_tran_locks; ``` In the output of the query you will get the `spid` which is waiting for a shared/exclusive lock.You can get the involved `spid's` by observing rows with same `res` and `resid` values. Further to get more information you can execute the following code to obtain connection, session, and blocking information about the processes involved in the blocking chain. ``` -- Connection info: SELECT -- use * to explore session_id AS spid, connect_time, last_read, last_write, most_recent_sql_handle FROM sys.dm_exec_connections WHERE session_id IN(--spid found in above query); -- Session info SELECT -- use * to explore session_id AS spid, login_time, host_name, program_name, login_name, nt_user_name, last_request_start_time, last_request_end_time FROM sys.dm_exec_sessions WHERE session_id IN(--spid found in above query); -- Blocking SELECT -- use * to explore session_id AS spid, blocking_session_id, command, sql_handle, database_id, wait_type, wait_time, wait_resource FROM sys.dm_exec_requests WHERE blocking_session_id > 0; --SQL text of the connections involved in the blocking chain: SELECT session_id, text FROM sys.dm_exec_connections CROSS APPLY sys.dm_exec_sql_text(most_recent_sql_handle) AS ST WHERE session_id IN(--spid found in above query); ``` Once you get involved spid's you can either KILL the spid using `KILL <spid>` command or set lock\_timeout in your stored procedure using command: `SET LOCK_TIMEOUT <milliseconds>;`
Timeouts are never in sql server, but always in the client calling them. So, if you can not tune the query (which may be the case) change the timeout in the application you use to issue the query.
The timeout period elapsed.. in my query
[ "", "sql", "sql-server", "sql-server-2008", "" ]
How I can write a query that can find me orders having same order lines (details)? Sample Data **Table: Order** ``` ORDER_ID -------- A B C D ``` **Table: OrderDetails** ``` OrderID ProductID ------------------ A ProductX A ProductY A ProductZ B ProductX B ProductY C ProductZ D ProductX D ProductY D ProductZ ``` Now I want to pass `ProductX,ProductY,ProductZ` and get back `A` and `D`. Can this be done in one query?
Maybe something like this is what you want? ``` SELECT DISTINCT Orders.OrderID FROM Orders INNER JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID WHERE OrderDetails.ProductID IN ('ProductX', 'ProductY', 'ProductZ') GROUP BY Orders.OrderID HAVING COUNT(*) = 3 ``` Also note that `Order` is a reserved keyword and should not be used as a table name.
``` SELECT OrderId FROM (SELECT DISTINCT o.OrderId, p.Product FROM Orders o INNER JOIN OrderDetails p ON o.OrderId = p .OrderId WHERE p.Product IN ('ProductX', 'ProductY', 'ProductZ') ) tab GROUP BY OrderId HAVING COUNT(*) = 3 ```
Sql Query for finding Orders having same order lines
[ "", "sql", "oracle", "" ]
I have the following question: For each city display the number of clients who only rented cars of type 'Toyota' or 'BMW' and never rented 'Mercedes' The tables are as follows: `Car [CarId int, type varchar(30)]` `Client [ClientId int, CityId int, Name varchar(30)]` `City [CityId int, CityName varchar(30)]` `Rent [CarId int, ClientId int, days_number int]` I don't know how would I formulate this query I tried hard but nothing worked until now.
Declare @count1 int, @count2 int Select @count1 = Count(\*) From Client inner join Rent on Client.ClientId = Rent.ClientId inner join Car on Car.CarId = Rent.CarId Where Car.type In( 'Toyota','BMW') --except Select @count2 = Count(\*) From Client inner join Rent on Client.ClientId = Rent.ClientId inner join Car on Car.CarId = Rent.CarId Where Car.type = 'Merccedes' Select (@count1 - @count2)
``` select city.cityname, count(*) as cnt from client join city on client.cityId = city.cityId where exists(select * from rent join car on rent.carid = car.carid where client.clientid = rent.clientid and car.[type] in ('Toyota', 'BMW')) and not exists(select * from rent join car on rent.carid = car.carid where client.clientid = rent.clientid and car.[type] = 'Mercedes') group by city.cityname ```
How could I form a tsql query with 'and' and 'not' for a result
[ "", "sql", "t-sql", "sql-server-2012", "" ]
I have data that is in two tables and I have a query combining the data as below. I am trying to eliminate duplicates based on the Id column where I pick the record with the oldest split date. Could anyone kindly assist me with the SQL statement to effect this? ``` |ID |SecID |ReportingDate |SplitDate |Adjustor| |1465 |2 |31-Dec-09 |01-Nov-10 |0.1 | |1465 |2 |31-Dec-09 |27-Dec-12 |0.2 | |1466 |2 |31-Dec-10 |27-Dec-12 |0.2 | |1468 |2 |31-Dec-11 |27-Dec-12 |0.2 | |1469 |2 |31-Dec-08 |01-Nov-10 |0.1 | |1469 |2 |31-Dec-08 |27-Dec-12 |0.2 | ``` The result should be as below: ``` |ID |SecId |ReportingDate |Adjustor | |1469 |2 |31-Dec-08 |0.1 | |1465 |2 |31-Dec-09 |0.1 | |1466 |2 |31-Dec-10 |0.2 | |1468 |2 |31-Dec-11 |0.2 | ``` More Information: Let me explain what I am trying to do here. In the fundamentals table I have a row with a unique Line Id, secId( a product identifier) and a reporting date for this line. This information needs to be adjusted using information from the splitdetails table that has a date from which it becomes applicable, the secId(product) it affects and the adjustor ratio to be used. For each line in fundamentals table: -Where any secId that doesnt have an entry in the splits table, adjustor should be 1. -If secId is present in the Splits table, the split to be used is the oldest one whose date is older than the fundamentals table reporting date being checked. I am hoping to get results from the sample above would end up look like this: | ID |SecId |ReportingDate |Adjustor | |1469 2 31-Dec-08 0.1 |1465 2 31-Dec-09 0.1 |1466 2 31-Dec-10 0.2 |1468 2 31-Dec-11 0.2 |1467 2 31-Dec-12 1 The query I am using is SELECT Gotten.ID, Gotten.SecID, Gotten.ReportingDate, Gotten.SplitDate, Adjustor FROM (SELECT tblFundamentalsDetails.id, tblFundamentalsDetails.SecId, tblFundamentalsDetails.ReportingDate, tblSplitDetails.SplitDate, tblSplitDetails.Adjustor FROM tblFundamentalsDetails LEFT JOIN tblSplitDetails ON (tblFundamentalsDetails.ReportingDate
One approach, that should be ok in Access SQL (though you might need to change the aliases): ``` SELECT a.* FROM Table1 a INNER JOIN ( SELECT ID, sdate = min(SplitDate) FROM Table1 GROUP BY ID ) b ON a.ID = b.ID AND a.SplitDate = b.sdate ``` Also you could take the inner query and make its own qry in Access.
For test data in a table (or saved query) named [Source] ``` ID SecID ReportingDate SplitDate Adjustor ---- ----- ------------- ---------- -------- 1465 2 2009-12-31 2010-11-01 0.1 1465 2 2009-12-31 2012-12-27 0.2 1466 2 2010-12-31 2012-12-27 0.2 1468 2 2011-12-31 2012-12-27 0.2 1469 2 2008-12-31 2010-11-01 0.1 1469 2 2008-12-31 2012-12-27 0.2 ``` the following query has been tested and *actually does work in Access*: ``` SELECT Source.ID, Source.SecID, Source.ReportingDate, Source.Adjustor FROM Source INNER JOIN ( SELECT ID, MIN(SplitDate) AS MinOfSplitDate FROM Source GROUP BY ID ) AS MinDate ON MinDate.ID = Source.ID AND MinDate.MinOfSplitDate = Source.SplitDate ``` returning ``` ID SecID ReportingDate Adjustor ---- ----- ------------- -------- 1465 2 2009-12-31 0.1 1466 2 2010-12-31 0.2 1468 2 2011-12-31 0.2 1469 2 2008-12-31 0.1 ```
SQL Statement to eliminate duplicates based on value in another column
[ "", "sql", "ms-access", "group-by", "aggregate-functions", "" ]
For unit testing purposes I need to completely reset/clear SQLite3 databases. All databases are created in memory rather than on the file system when running the test suite so I can't delete any files. Additionally, several instances of a class will be referencing the database simultaneously, so I can't just create a new database in memory and assign it to a variable. Currently my workaround for clearing a database is to read all the table names from `sqlite_master` and drop them. This is not the same as completely clearing the database though, since meta data and other things I don't understand will probably remain. Is there a clean and simple way, like a single query, to clear a SQLite3 database? If not, what would have to be done to an existing database to make it identical to a completely new database? --- In case it's relevant, I'm using Ruby 2.0.0 with [sqlite3-ruby](https://github.com/sparklemotion/sqlite3-ruby) version 1.3.7 and SQLite3 version 3.8.2.
This works without deleting the file and without closing the db connection: ``` PRAGMA writable_schema = 1; DELETE FROM sqlite_master; PRAGMA writable_schema = 0; VACUUM; PRAGMA integrity_check; ``` Another option, if possible to call the C API directly, is by using the `SQLITE_DBCONFIG_RESET_DATABASE`: ``` sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0); sqlite3_exec(db, "VACUUM", 0, 0, 0); sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0); ``` Here is the [reference](https://www.sqlite.org/c3ref/c_dbconfig_defensive.html#sqlitedbconfigresetdatabase)
**The simple and quick way** If you use in-memory database, the fastest and most reliable way is to close and re-establish sqlite connection. It flushes any database data and also per-connection settings. If you want to have some kind of "reset" function, you must assume that no other threads can interrupt that function - otherwise any method will fail. Therefore even you have multiple threads working on that database, there need to be a "stop the world" mutex (or something like that), so the reset can be performed. While you have exclusive access to the database connection - why not closing and re-opening it? **The hard way** If there are some other limitations and you cannot do it the way above, then you were already pretty close to have a complete solution. If your threads don't touch pragmas explicitly, then only "schema\_version" pragma can be changed silently, but if your threads can change pragmas, well, then you have to go through the list on <http://sqlite.org/pragma.html#toc> and write "reset" function which will set each and every pragma value to it's initial value (you need to read default values at the begining). Note, that pragmas in SQLite can be divided to 3 groups: 1. defined initially, immutable, or very limited mutability 2. defined dynamically, per connection, mutable 3. defined dynamically, per database, mutable Group 1 are for example page\_size, page\_count, encoding, etc. Those are definied at database creation moment and usualle cannot be modified later, with some exceptions. For example page\_size can be changed prior to "VACUUM", so the new page size will be set then. The page\_count cannot be changed by user, but it changes automatically when adding data (obviously). The encoding is defined at creation time and cannot be modified later. You should not need to reset pragmas from group 1. Group 2 are for example cache\_size, recursive\_triggers, jurnal\_mode, foreign\_keys, busy\_timeout, etc. These pragmas are always set to defaults when opening new connection to the database. If you don't disconnect, you will need to reset those to defaults manually. Group 3 are for example schema\_version, user\_version, maybe some others, you need to look it up. Those will also need manual reset. If you disconnect from in-memory database, the database gets destroyed, so then you don't need to reset those.
How do I completely clear a SQLite3 database without deleting the database file?
[ "", "sql", "sqlite", "" ]
Hi i need a bit of help with the SQL query below ``` DECLARE @company nvarchar(50) DECLARE @theweek date SET @company = 'RWF' SET @theweek = '2014-02-03' SELECT [thedate],[PRN],[StartTime] ,[FinishTime],[Grade],[BreakTime],[TotalCost],[Department],[CompanyCode] FROM LabourHireCost WHERE thedate BETWEEN @THEWEEK AND CONVERT(datetime, @theweek) +7 ORDER BY CompanyCode, PRN, thedate ``` this return result like this( below ) but what i would like to do if possible is return the employee and the times worked for the week ``` Thedate PRN Start Finish Grade Break Cost Department Company | 2014-02-03 | 179 | 06:00 | 06:00 | 2 | 01:00 | 26.17 | 2 | DH | | 2014-02-04 | 179 | 06:00 | 06:00 | 3 | 01:00 | 36.17 | 2 | DH | | 2014-02-03 | 178 | 06:00 | 06:00 | 2 | 01:00 | 26.17 | 2 | DH | | 2014-02-04 | 178 | 06:00 | 06:00 | 4 | 01:00 | 46.17 | 2 | DH | ``` i was thinking of something like this ``` PRN 179 Thedate Start Finish Grade Break Cost Department Company | 2014-02-03 | 06:00 | 06:00 | 2 | 01:00 | 26.17 | 2 | DH | | 2014-02-04 | 06:00 | 06:00 | 3 | 01:00 | 36.17 | 2 | DH | PRN 178 | 2014-02-03 | 06:00 | 06:00 | 2 | 01:00 | 26.17 | 2 | DH | | 2014-02-04 | 06:00 | 06:00 | 4 | 01:00 | 46.17 | 2 | DH | ```
Based on your current results vs. expected results, it looks like the query is already returning the data that you want. If you want to present it differently, that would be done in your client application (whether it is web app, reporting software, or even Excel), but SQL Server generally should not be used for breaking datasets into nicely formatted reports.
Well how about using a cte to calculate the amount of time everyone (time frame between start and finish )worked on x date and then selecting it?
SQL query group rows by column PRN
[ "", "sql", "sql-server", "sql-server-2008", "" ]
I am trying to get the unpaid and partial amount separately in single query ``` select if(i.status = 'unpaid', sum(i.total_amount), '') unpaid, if(i.status = 'partial', sum(i.paid_amount), '') partial from {CI}invoices i where i.customer_id = ? and date(i.invoice_date) < '2014-01-01' and i.status not like 'paid%' ``` But i am getting blank i think that is because i used `''` in if statement, i also tried with ``` if(i.status = 'unpaid', sum(i.total_amount) as unpaid, sum(i.paid_amount) as paid) ``` which is wrong because i can't use `as` in `IF()` condition. Can anyone please help me to resolve this query or suggest any alternative way??
Try the following: ``` SELECT SUM( IF(i.status = 'unpaid', i.total_amount, 0) ) unpaid, SUM( IF(i.status = 'partial', i.paid_amount, 0) ) partial FROM {CI}invoices i WHERE i.customer_id = ? AND date(i.invoice_date) < '2014-01-01' AND i.status IN ('unpaid', 'partial') ```
Give this a go: ``` select sum(case when i.status = 'unpaid' then i.total_amount else 0 end) as unpaid, sum(case when i.status = 'partial' then i.paid_amount else 0 end) as partial from {CI}invoices i where i.customer_id = ? and date(i.invoice_date) < '2014-01-01' and i.status not like 'paid%' ```
How to get separate fields data with IF() statement in single query
[ "", "mysql", "sql", "" ]
I am executing the below query and using alias name for all columns. I have named alias with a . since that is a requirement. now, I want to refer to the alias name directly in the where clause and i do is as given below: ``` SELECT pt.prod_desc AS"PROD_DESC", ( CASE WHEN pt.prod_level='2' THEN 'Product' WHEN pt.prod_level='4' THEN 'Sub-Product' WHEN pt.prod_level='5' THEN 'Service' ELSE 'N/A' END) AS"PROD_LEVEL", prod_id AS "PROD_ID", isactive AS "IsActive", updt_usr_sid AS "UPDT_USR_SID", updt_ts AS "UPDT_TS", ( CASE WHEN pt.prod_level='5' THEN parent_prod_id ELSE NULL END) AS ".SUB_PROD_ID", ( CASE WHEN pt.prod_level='5' THEN (SELECT prod_desc FROM dims_prod_type A WHERE A.prod_id= pt.parent_prod_id ) ELSE 'N/A' END ) AS ".SUB_PROD_DESC", ( CASE WHEN pt.prod_level='4' THEN parent_prod_id WHEN pt.prod_level='5' THEN (SELECT parent_prod_id FROM dims_prod_type A WHERE A.prod_id= pt.parent_prod_id ) ELSE NULL END) AS ".PRNT_PROD_ID", ( CASE WHEN pt.prod_level='4' THEN (SELECT prod_desc FROM dims_prod_type A WHERE A.prod_id=pt.parent_prod_id ) WHEN pt.prod_level='5' THEN (SELECT prod_desc FROM dims_prod_type A WHERE A.prod_id IN (SELECT B.parent_prod_id FROM dims_prod_type B WHERE b.prod_id=pt.parent_prod_id ) ) ELSE 'N/A' END)AS ".PRNT_PROD_DESC" FROM dims_prod_type pt WHERE pt.".PRNT_PROD_ID" like 'A%'; ``` However when i am executing this I get the following error: ``` SQL Error: ORA-00904: "PT".".PRNT_PROD_ID": invalid identifier 00904. 00000 - "%s: invalid identifier" ``` I know that SQL executes the where clause first and hence that is the reason of the error. But how do i fix this? Any suggestions please?
You already know you [can't use the alias in the `where` clause](http://docs.oracle.com/cd/E11882_01/server.112/e26088/queries002.htm#sthref2213), but that only applies in the same level of SQL. You can wrap your query in an outer query: ``` SELECT * FROM ( SELECT pt.prod_desc AS"PROD_DESC", ... END)AS ".PRNT_PROD_DESC" FROM dims_prod_type pt ) WHERE ".PRNT_PROD_ID" like 'A%'; ``` The only alternative would be to repeat the whole `case` that generates that column in the `where` clause, which would be unpleasant with something so complicated.
Put the query in a subquery, then you can refer to the aliases in your where clause, e.g.: ``` SELECT * FROM ( SELECT pt.prod_desc AS"PROD_DESC", ...etc... FROM dims_prod_type pt) pt WHERE pt.".PRNT_PROD_ID" like 'A%'; ```
Using alias name in WHERE clause
[ "", "sql", "oracle", "column-alias", "" ]
have table like this : ``` user_id Date Status 1000 2013-04-02 11:46:10.000 IN 1001 2013-04-02 11:50:08.000 OUT 1005 2013-04-02 11:46:24.000 IN 1005 2013-04-02 12:50:04.000 OUT 1005 2013-04-02 12:50:10.000 OUT 1045 2013-04-02 14:46:05.000 IN ``` Want delete date where status IN or OUT is twice for one user. For example it must delete user\_id 1005 where date is 2013-04-02 12:50:04.000 . I want leave only latest date
You can use a [CTE](http://msdn.microsoft.com/en-us/library/ms175972.aspx) + `ROW_NUMBER`: ``` WITH CTE AS ( SELECT user_id, Date, Status, RN = ROW_NUMBER () OVER (PARTITION BY user_id, Status ORDER BY Date DESC) FROM dbo.TableName ) DELETE FROM CTE WHERE RN > 1 ``` You can use `SELECT * FROM` to see what you're going to delete. Here's a `Demo` with your sample data.
This answer will also work for older versions of mssql ``` delete t from table t where exists(select 1 from table where t.user_id = user_id and t.status = status and t.date < date) ``` The weakness of this answer is that if you have a senario with the same timestamp, the same user\_id and the same date on 2 rows it will leave both rows intact
Delete rows with date check
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "" ]
I have two oracle select statememts, selecting data from same table. ``` SELECT empid, empname, days, SUM (amount) Amount1 FROM tbl_details WHERE particulars IN ('Basic Pay', 'Allowances') GROUP BY empid, empname, days SELECT empid, empname, days, SUM (amount) Amount2 FROM tbl_details WHERE particulars IN ('Water Charge', 'Housing Allowance') GROUP BY empid, empname,tdays ``` I want to bind this to one select statement so that I will get one resulatant, having columns empid,empname,days,Amount1,Amount2 Can anyone please help me doing this? Thanks in advance.
I think below will help you ``` SELECT empid, empname, days, Sum (CASE WHEN particulars IN ( 'Water Charge', 'Housing Allowance' ) THEN amount ELSE 0 END) Amount2, Sum (CASE WHEN particulars IN ( 'Basic Pay', 'Allowances' ) THEN amount ELSE 0 END) Amount1 FROM tbl_details GROUP BY empid, empname, days ```
Use a [UNION](http://www.techonthenet.com/sql/union.php): ``` SELECT empid, empname, days, SUM (amount) Amount FROM tbl_details WHERE particulars IN ('Basic Pay', 'Allowances') GROUP BY empid, empname, days UNION SELECT empid, empname, days, SUM (amount) Amount FROM tbl_details WHERE particulars IN ('Water Charge', 'Housing Allowance') GROUP BY empid, empname,tdays ``` By default a union will eliminate duplicate records, if you would like to keep the duplicate records replace `UNION` with `UNION ALL`
Bind two select statements
[ "", "sql", "oracle", "select", "join", "subquery", "" ]
I recently encountered a problem caused by a typo in the database creation script, whereby a column in the database was created as `varchar(0)` instead of `varchar(20)`. I expected that I would have gotten an error for 0-length string field, but I didn't. What is the purpose of `varchar(0)` or `char(0)` as I wouldn't be able to store any data in this column anyway.
It's not allowed per the [SQL-92](http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt) standard, but permitted in MySQL. From the [MySQL manual](http://dev.mysql.com/doc/refman/5.0/en/string-type-overview.html): > MySQL permits you to create a column of type `CHAR(0)`. This is useful primarily when you have to be compliant with old applications that depend on the existence of a column but that do not actually use its value. `CHAR(0)` is also quite nice when you need a column that can take only two values: A column that is defined as `CHAR(0)` NULL occupies only one bit and can take only the values `NULL` and `''` (the empty string).
Just checked MySQL, it's true that it allows zero-length CHAR and VARCHAR. Not that it can be extremely useful but I can think of a situation when you truncate a column to 0 length when you no longer need it but you don't want to break existing code that writes something there. Anything you assign to a 0-length column will be truncated and a warning issued, but warnings are not errors, they don't break anything.
What's the purpose of varchar(0)
[ "", "mysql", "sql", "sqldatatypes", "" ]
I need to query two columns "oc\_filter\_group\_description.name" and "oc\_filter.name" and get all matching results. The alias seems to be causing me the problem. I've tried using a sub query but being a complete novice I really don't know what I'm doing. Here is the code as it stands. The OR clause is what needs adapting ``` SELECT *,(SELECT name FROM oc_filter_group_description fgd WHERE f.filter_group_id = fgd.filter_group_id) AS `group` FROM oc_filter f LEFT JOIN oc_filter_description fd ON (f.filter_id = fd.filter_id) WHERE fd.name LIKE '% **QUERY GOES HERE** %' OR 'group' LIKE '% **QUERY GOES HERE** %' ``` I have spent far too long trying to get this to work I thought I better call in re-enforcements. Thanks in advance
You can't reference column aliases defined in the `select` in the `where` clause. This is your query: ``` SELECT *, (SELECT name FROM oc_filter_group_description fgd WHERE f.filter_group_id = fgd.filter_group_id ) AS `group` FROM oc_filter f LEFT JOIN oc_filter_description fd ON f.filter_id = fd.filter_id WHERE fd.name LIKE '% **QUERY GOES HERE** %' OR 'group' LIKE '% **QUERY GOES HERE** %'; ``` It has two obvious problems. The first is that `'group'` is a string constant not a column reference. *Only* use single quotes for string literals. It avoids this type of problem. The second is that it refers to the `group` defined in the `select` clause. The best solution is to replace the subquery in the `select` with another `join`: ``` SELECT *, fgd.name as group_name FROM oc_filter f LEFT JOIN oc_filter_description fd ON f.filter_id = fd.filter_id LEFT JOIN oc_filter_group_description fgd ON f.filter_group_id = fgd.filter_group_id WHERE fd.name LIKE '% **QUERY GOES HERE** %' OR fgd.name LIKE '% **QUERY GOES HERE** %'; ``` Note that I also changed the name `group` to `group_name`, so it doesn't conflict with a MySQL reserved words. Voila, no quotes are needed.
This might look a minor thing, but you shouldn't use backticks and whenever possible avoid keywords: ``` SELECT *, ( SELECT name FROM oc_filter_group_description fgd WHERE f.filter_group_id = fgd.filter_group_id) AS T_GROUP FROM oc_filter f LEFT JOIN oc_filter_description fd ON (f.filter_id = fd.filter_id) WHERE fd.name LIKE '% **QUERY GOES HERE** %' OR T_GROUP LIKE '% **QUERY GOES HERE** %' ``` Hope this helped.
multiple tables OR clause and with alias
[ "", "mysql", "sql", "opencart", "" ]
I have 2 tables: `'matches'` and `'players'`. In 'matches' I have individual goals scored and who by. In 'players' I have individual players and goals scored. How do I automatically update the player's total goals scored in the 'players' table when the players name gets a goal next to it in the 'matches' table?
I would create a third table `GOALS`. ``` create table GOALS( GOAL_ID INT, PLAYER_ID INT, MATCH_ID INT, GOAL_TIME DATE, ETC... ); ``` Then use this table to join to the `PLAYERS` and `MATCHES` tables. This allows all `GOALS` to be stored in one location. If you need to determine the amount of goals scored by a player or during a match you can execute a simple `count()` against the goals table.
Try this one ``` Here third table needed create table GOAL( GID INT(PK), PID INT(FK of players), MID INT (FK of matches) ); when This (GOAL) inserted then use a trigger used and update goal of players CREATE TRIGGER ins_trig AFTER INSERT ON GOAL -> FOR EACH ROW -> BEGIN -> UPDATE players SET goals scored(GIVE THE CONDITION); -> END; ```
mysql: update 2 tables based on 1 input
[ "", "mysql", "sql", "" ]
Does anyone have a good approach for generating a daily summary from a table containing intervals of times given by start and stop dates (where a null stop means continues indefinitely)? The best way to describe the problem is with an example. Imagine a database tracking schedules for workers at a restaurant, where employees are hired and fired frequently. Sometimes employees might come back and get rehired. Given a table with one row for each employee like the following: ``` position,name,start,end bottle washer,Fred,1/2/2013,1/5/2013 bottle washer,Barney,1/4/2013,1/7/2013 bottle washer,Betty,1/10/2013, bottle washer,Wilma,1/12/2013,1/13/2013 cook,Bilbo,1/1/2013,1/3/2013 cook,Frodo,1/5/2013,1/8/2013 cook,Bilbo,1/7/2013 ``` I'm looking for a query that produces one row for each day/position giving the staffing level for that day, as in: ``` position,date,staffing bottle washer,1/1/2013,0 bottle washer,1/2/2013,1 bottle washer,1/3/2013,1 bottle washer,1/4/2013,2 bottle washer,1/5/2013,2 bottle washer,1/6/2013,1 bottle washer,1/7/2013,1 bottle washer,1/8/2013,0 bottle washer,1/9/2013,0 bottle washer,1/10/2013,1 bottle washer,1/11/2013,1 bottle washer,1/12/2013,2 bottle washer,1/13/2013,2 bottle washer,1/14/2013,1 bottle washer,1/15/2013,1 cook,1/1/2013,1 cook,1/2/2013,1 cook,1/3/2013,1 cook,1/4/2013,0 cook,1/5/2013,1 cook,1/6/2013,1 cook,1/7/2013,2 cook,1/8/2013,2 cook,1/9/2013,1 cook,1/10/2013,1 cook,1/11/2013,1 cook,1/12/2013,1 cook,1/13/2013,1 cook,1/14/2013,1 cook,1/15/2013,1 ``` I realize that I could solve this problem by writing procedural code on the client side or a stored procedure on the server side, but it would simplify alot of things to use a single SQL query. It would be fine if it were a complicated query or if it used windowing or analytic functions. At the moment, we're using Oracle if that matters. Any suggestions on good approaches?
A partition outer join can help fill in calendar data. It is similar to a cross join but may perform much better with non-trivial table sizes. A cross join will join every row in set A with every row in set B. A partition outer join will join every row in set A with every defined subset in set B. The example below generates the date range only based on the schedule data you provided. Therefore the 14th and 15th do not show up, but that can be easy to fix. ``` with schedules as ( --Schedule data. select 'bottle washer' position, 'Fred' name, date '2013-01-02' startdate, date '2013-01-05' enddate from dual union all select 'bottle washer' position, 'Barney' name, date '2013-01-04' startdate, date '2013-01-07' enddate from dual union all select 'bottle washer' position, 'Betty' name, date '2013-01-10' startdate, null enddate from dual union all select 'bottle washer' position, 'Wilma' name, date '2013-01-12' startdate, date '2013-01-13' enddate from dual union all select 'cook' position, 'Bilbo' name, date '2013-01-01' startdate, date '2013-01-03' enddate from dual union all select 'cook' position, 'Frodo' name, date '2013-01-05' startdate, date '2013-01-08' enddate from dual union all select 'cook' position, 'Bilbo' name, date '2013-01-07' startdate, null enddate from dual ), dates as ( --Date range, based on schedule data. select first_startdate + level - 1 the_date from ( select min(startdate) first_startdate ,(max(enddate) - min(startdate))+1 date_diff from schedules ) connect by level <= date_diff ) --Count of staff working per position, per day. select position, the_date, count(schedules.startdate) staffing from dates left join schedules partition by (position) on dates.the_date between schedules.startdate and nvl(schedules.enddate, date '9999-12-31') group by position, the_date order by position, the_date; ```
I have used a CTE with the sample data that you have provided. I have also changed a few column names to allow me to execute the query. The example is as follows: ``` WITH tbl AS (SELECT 'bottle washer' AS position, 'Fred' AS name, to_date ('01/02/2013', 'mm/dd/yyyy') AS startdate, to_date ('01/05/2013', 'mm/dd/yyyy') AS enddate FROM dual UNION ALL SELECT 'bottle washer', 'Barney', to_date ('01/04/2013', 'mm/dd/yyyy'), to_date ('01/07/2013', 'mm/dd/yyyy') FROM dual UNION ALL SELECT 'bottle washer', 'Betty', to_date ('01/10/2013', 'mm/dd/yyyy'), NULL FROM dual UNION ALL SELECT 'bottle washer', 'Wilma', to_date ('01/12/2013', 'mm/dd/yyyy'), to_date ('01/13/2013', 'mm/dd/yyyy') FROM dual UNION ALL SELECT 'cook', 'Bilbo', to_date ('01/01/2013', 'mm/dd/yyyy'), to_date ('01/03/2013', 'mm/dd/yyyy') FROM dual UNION ALL SELECT 'cook', 'Frodo', to_date ('01/05/2013', 'mm/dd/yyyy'), to_date ('01/08/2013', 'mm/dd/yyyy') FROM dual UNION ALL SELECT 'cook', 'Bilbo', to_date ('01/07/2013', 'mm/dd/yyyy'), NULL FROM dual), daterange AS ( SELECT to_date ('01-JAN-2013') + rownum - 1 AS dd FROM dual CONNECT BY rownum <= 15 START WITH rownum = 1) SELECT t.position, to_char(d.dd, 'mm/dd/yyyy') as "date", count ( CASE WHEN t.enddate IS NOT NULL AND d.dd BETWEEN t.startdate AND t.enddate THEN 1 WHEN t.enddate IS NULL AND d.dd >= t.startdate THEN 1 ELSE NULL END) AS staffing FROM tbl t CROSS JOIN daterange d GROUP BY t.position, d.dd ORDER BY t.position, d.dd; ``` **OUTPUT:** ``` POSITION DATE STAFFING ---------------- ------------- --------- bottle washer 01/01/2013 0 bottle washer 01/02/2013 1 bottle washer 01/03/2013 1 bottle washer 01/04/2013 2 bottle washer 01/05/2013 2 bottle washer 01/06/2013 1 bottle washer 01/07/2013 1 bottle washer 01/08/2013 0 bottle washer 01/09/2013 0 bottle washer 01/10/2013 1 bottle washer 01/11/2013 1 bottle washer 01/12/2013 2 bottle washer 01/13/2013 2 bottle washer 01/14/2013 1 bottle washer 01/15/2013 1 cook 01/01/2013 1 cook 01/02/2013 1 cook 01/03/2013 1 cook 01/04/2013 0 cook 01/05/2013 1 cook 01/06/2013 1 cook 01/07/2013 2 cook 01/08/2013 2 cook 01/09/2013 1 cook 01/10/2013 1 cook 01/11/2013 1 cook 01/12/2013 1 cook 01/13/2013 1 cook 01/14/2013 1 cook 01/15/2013 1 ```
Is there a good SQL approach for summarizing a table with blocks of date ranges as input?
[ "", "sql", "oracle", "" ]
I am creating a high scores table stored on a database for my game, but I was wondering the best practices are for storing such tables. Should the table be resorted each time a new score is added or should the data being received by a query just be sorted? It seems like it would be easier on the server to just sort when retrieving data instead of updating the table each time.
Rows in a relational database such as MySQL, Oracle, PostgreSQL, etc. are not maintained in any order. In the theory of relational databases result sets are returned in no specified order unless the query contains an `ORDER BY` clause. Any ordering is (must be) applied each time the data is retrieved. Implementations may, in some cases, store the data in some order, but they are not required to do so. In fact, if you run the exact same query twice on the same data there is no guarantee that the data will be returned in the same sequence. In other words, you cannot impose a storage order on your data, you impose order only on result sets at the time the query is executed.
I recommend sorting the data in your MySQL query. As you said it is easier to only sort when needed, not when every record is added.
Are database tables sorted before or after being retrieved?
[ "", "mysql", "sql", "database", "" ]
i have this tables: Table1: ``` id Name 1 Example1 2 Example2 ``` Table2: ``` id Date.............. 1 5.2.2014........ 1 6.2.2014......... 1 6.2.2014........ 2 16.1.2014....... 2 17.1.2014....... ``` And I need take id and Name from table1 and join table1.id = table2.id and from table2 take only top 1 row... Example: ``` id Name Date 1 Example1 5.2.2014 2 Example2 16.1.2014 ``` It is possible?
You can use `row_number()` to filter out all but the latest row per `id`: ``` select * from ( select row_number() over (partition by id order by Date desc) as rn , * from Table2 ) as t2 join Table1 as t1 on t1.id = t2.id where t2.rn = 1 -- Only latest row ```
Well, a simple attempt would be ``` SELECT t1.*, (SELECT TOP 1 t2.Date FROM Table2 t2 WHERE t2.ID = t1.ID t2.Date) t2Date FROM Table1 t1 ``` If you were using SQL Server, you could use [ROW\_NUMBER](http://technet.microsoft.com/en-us/library/ms186734.aspx) Something like ``` ;WITH Vals AS ( SELECT t1.ID, t1.Name, t2.Date, ROW_NUMBER() OVER(PARTITION BY t1.ID ORDER BY t2.Date) RowID FROm Table1 t1 LEFT JOIN Table2 t2 ON t1.ID ) SELECT * FROM Vals WHERE RowID = 1 ```
Join data from two tables and top from table 2
[ "", "sql", "" ]
I'm trying to create a IF NOT EXISTS query in Oralce like this: ``` DECLARE cnt NUMBER; BEGIN SELECT COUNT(*) INTO cnt FROM MY.MYTABLE WHERE MYFIELD = 400; IF (cnt = 0) THEN SELECT 'NO ROWS' AS FAIL FROM DUAL; ELSE SELECT 'SOME ROWS' AS PASS FROM DUAL; END IF; END; ``` but this fails for ``` ORA-06550: line 9, column 7: PLS-00428: an INTO clause is expected in this SELECT statement ORA-06550: line 11, column 7: PLS-00428: an INTO clause is expected in this SELECT statement ``` Why, what is wrong with this query?
Use into to assign value to variable. ``` DECLARE cnt NUMBER; res NVARCHAR2(50); BEGIN SELECT COUNT(*) INTO cnt FROM MY.MYTABLE WHERE MYFIELD = 400; IF (cnt = 0) THEN SELECT 'NO ROWS' INTO RES FROM DUAL; ELSE SELECT 'SOME ROWS' INTO RES FROM DUAL; END IF; END; ``` Also you can directly assign value to variable like ``` IF (cnt = 0) THEN res := 'NO ROWS'; ELSE res := 'SOME ROWS'; END IF; ``` Best way is just using this sql ``` SELECT DECODE(COUNT(*), 0, 'NO ROWS','SOME ROWS') FROM MY.MYTABLE WHERE MYFIELD = 400; ```
I prefer this way of checking for existence: ``` declare dummy varchar2(1); begin select null into dummy from MY.MYTABLE where MYFIELD = 400 and rownum = 1; dbms_output.put_line('some rows'); -- some rows exception when no_data_found then dbms_output.put_line('no rows'); -- no rows end; ``` in my opinion it is better because count() can work quite slow for big amounts of data.
How to create a IF NOT EXISTS query in Oracle?
[ "", "sql", "oracle", "" ]
I have a table which looks like ``` MyTable ( Student ID, Exam) ``` I want to place a trigger/constraint which describes: A student ID can appear many times and does not have to be unique. However, the pair (Student ID, "French") can only appear once. So each student can only have one "French" entry. French is hardcoded ``` ID Exam 0001 German 0001 History 0001 French 0001 French <-- This insert should fail. ``` Attemting to update the "German" field to French should also fail So far I've tried ``` CREATE OR REPLACE TRIGGER MyTrigger BEFORE INSERT OR UPDATE ON MyTable FOR EACH ROW DECLARE rowsCount INTEGER; BEGIN select count(*) INTO rowsCount from MyTable sc where SC.SC_TYPE = 'FRENCH' and :new.StudentID = sc.StudentID; IF rowsCount > 1 THEN raise_application_error('-20098','You cannot have more than one French record per student.'); END IF; end; ``` This is throwing a Mutate error though. Anyway, this is related to integrity, so I'm sure a constraint would be better, but would appreciate some advice on how to accomplish this.
Yes, French can only appear once per student, but everything else can appear multiple times. I'm thinking perhaps this is best solved with a index? Similar to: [Oracle SQL Constraint where clause](https://stackoverflow.com/questions/12177369/oracle-sql-constraint-where-clause) ``` CREATE UNIQUE INDEX MyIndex ON MyTable( CASE WHEN Exam= 'French' THEN StudentID ELSE NULL END ); ```
Because of the specialized nature of the restriction (only French is restricted) I don't think this can be done with a constraint (although I'd be glad to learn otherwise). One way you CAN solve it is to use a statement trigger: ``` CREATE OR REPLACE TRIGGER NO_DUPLICATE_FRENCH_TRIGGER BEFORE INSERT OR UPDATE ON MY_TABLE -- NOTE: NO 'FOR EACH ROW', which means this is fired once for each -- statement executed, rather than once for each row modified. DECLARE nMax_count NUMBER; BEGIN SELECT MAX(COUNT_VAL) INTO nMax_count FROM (SELECT STUDENTID, COUNT(*) AS COUNT_VAL FROM MY_TABLE WHERE EXAM = 'FRENCH' GROUP BY STUDENTID); IF nMax_count > 1 THEN RAISE SOME_EXCEPTION; END IF; END NO_DUPLICATE_FRENCH_TRIGGER; ``` Statement triggers have the advantage that they're not subject to the "mutating table" issue as is a row trigger. However, this is a bit of a kluge, introduces a full table scan, and if the table is large may be a performance issue, but at least it's A solution. Share and enjoy.
Trigger/Constraint to restrict inserts or updates
[ "", "sql", "oracle", "plsql", "triggers", "" ]
Question: > Write a SELECT statement that returns these column names and data from the Products table: > > ProductName - The ProductName column > > ListPrice - The ListPrice column > > DiscountPercent - The DiscountPercent column > > DiscountAmount - A column that’s calculated from the previous two columns > > DiscountPrice - A column that’s calculated from the previous three columns > > Sort the result set by DiscountPrice in descending sequence. I have gotten to the first calculation, calculating the DiscountAmount. Now, I have to calculate the DiscountPrice by subtracting ListPrice - DiscountPercent - DiscountAmount (which is an alias). I cannot seem to figure this out. My code so far is below: ``` SELECT ProductName, ListPrice, DiscountPercent, ListPrice - DiscountPercent AS DiscountAmount FROM Products; ```
There are several ways this can be done. The common table expression (CTE method) Ex: ``` ;With Data As ( SELECT ProductName, ListPrice, DiscountPercent, ListPrice - DiscountPercent AS DiscountAmount FROM Products ) Select ProductName, ListPrice, DiscountPercent, DiscountAmount, ListPrice-DiscountAmount As DiscountPrice From Data; ``` Personally, I don't care for this method when it's something relatively simple like this. Instead, I usually repeat the calculation when necessary. Like this: ``` Select ProductName, ListPrice, DiscountPercent, ListPrice - DiscountPercent As DiscountAmount, ListPrice- (ListPrice - DiscountPercent) As DiscountPrice From Products; ``` By the way, I think your calculation for DiscountAmount is wrong. Since this is a learning experience, I suggest you double check that part. Please note that I did not correct this part of the code even though I think it is wrong.
Seems like G.Mastros forgot to sort the result set by discount price in descending sequence. So your whole query should be ``` SELECT ProductName, ListPrice, DiscountPercent, ListPrice - DiscountPercent As DiscountAmount, ListPrice - (ListPrice - DiscountPercent) As DiscountPrice FROM Products ORDER BY DiscountPrice DESC ```
Calculating column when an ALIAS is involved
[ "", "sql", "sql-server", "alias", "" ]
I need to replace a `NULL` value in a column only when other conditions are matched. ``` Columns: Parent, Child, flag01, lag02 ``` Parent columns has many `NULL` values, but I want to replace the `null` values only when `flag01` and `flag02` is "ok". If `flag01` and `flag02` are both "`Ok`" and Parent is NULL, replace to 'CT\_00000'. Else, keep the original value (when NOT NULL).
So as I though you want a select statement. ``` select case when (parent is null and flag01 = 'OK' and flag02 = 'OK') then 'CT_00000' else parent end as columnSomeName, Child, flag01, lag02 from yourTable ```
``` UPDATE Table_Name SET Column_Name = 'CT_00000' WHERE flag01 = 'OK' AND flag02 = 'OK' AND Parent IS NULL ``` just to select data ``` SELECT CASE WHEN (flag01 = 'OK' AND flag02 = 'OK' AND Parent IS NULL) THEN 'CT_00000' ELSE Column_Name END AS Column_Name FROM Table_Name ```
Change column value when matching condition
[ "", "sql", "oracle", "" ]
I'm creating a traffic report for my company but I'm really stuck on this piece of code.. I have a report number, and type of accidents denoted by number i.e; 1-slight, 2-serious, 3-fatal and 4-not injured. usually an accident report contains more than one number, for instance: a report number 2014123 has a driver with serious injury '2', passenger Not Injured '4'. so when i fire the select query where report number=2014123 , i get two records, one with '2' injury and the other with '4'. in the above scenario, the accident is treated as 'Serious' since it contains '2'. '4' is not considered since the passenger is not injured. injury codes with (slight, serious, fatal) are treated higher than (not injured). How can I generate the report with serious injury (i.e; code '2') and the injury count as '2'(since two records)? Methods I have tried: I tried with the SQL Case statement: ``` (Case WHEN InjuryCode IN ('1','2','4') THEN 'Serious' WHEN InjuryCode IN ('1','2','3','4') THEN 'FATAL' WHEN InjuryCode IN ('1','4') THEN 'SLIGHT' ELSE 'UNKNOWN' END) AS ACCIDENT_STATUS ``` but all i got was duplicating and incorrect data. the injury code is given preference in the following manner: 3>2>1>4 eg: an accident with contains injurycode as: ``` 1,4- slight 2,4- serious 3,4- fatal ``` 1,2,3,4-fatal (because 3 is the highest injury code) etc etc.. I hope this doesn't get you confused, but kindly bear with me, ,i was totally confused at the beginning, but i am actually getting the picture now, although without a solution, please help! EDIT (the full query from the comment): ``` SELECT REPORTNUMBER, INJURYCODE, (CASE WHEN InjuryCode IN ('1','2','4') THEN 'Serious' WHEN INJURYCODE IN ('1','2','3','4') THEN 'FATAL' WHEN INJURYCODE IN ('1','4') THEN 'SLIGHT' ELSE 'UNKNOWN' END) AS ACCIDENT_STATUS FROM ACCIDENTS WHERE REPORTNUMBER=20140302 ```
The use of `injuryCode` suggests that you need an `Injury` table (if you don't have one already). Ideally, this includes some sort of severity column that you could order by - something like this: ``` CREATE TABLE Injury (injuryCode CHAR(1), severity INTEGER, description VARCHAR(20)); INSERT INTO Injury VALUES ('1', 1, 'Slight'), ('2', 2, 'Serious'), ('3', 3, 'Fatal'), ('4', 0, 'Not Injured'); ``` Strictly speaking, what you were attempting before was sorting based on an apparent id of the injury - the only thing ids should be used for is joins, and should otherwise be considered random/undefined values (that is, the actual value is unimportant - it's whether there's anything *connected to it* that's important). The fact that these happen to be numerical codes (apparently stored as character data - this is perfectly acceptable) is immaterial. Regardless, with a sorting table defined, we can now safely query the data: ``` SELECT AggregateAccident.reportNumber, Injury.injuryCode, Injury.description, AggregateAccident.victimCount FROM (SELECT Accidents.reportNumber, MAX(Injury.severity) as severity, COUNT(*) as victimCount FROM Accidents JOIN Injury ON Injury.injuryCode = Accidents.injuryCode GROUP BY Accidents.reportNumber) AggregateAccident JOIN Injury ON Injury.severity = AggregateAccident.severity ORDER BY AggregateAccident.reportNumber ``` (And [SQL Fiddle example](http://sqlfiddle.com/#!6/87f9b/4). Thanks to Turophile for the skeleton. Using SQL Server, but this should work on any RDBMS). --- # EDIT: If you can't create a permanent table, you can create a temporary one: ``` WITH Injury AS (SELECT a AS injuryCode, b AS severity, c AS description FROM (VALUES ('1', 1, 'Slight'), ('2', 2, 'Serious'), ('3', 3, 'Fatal'), ('4', 0, 'Not Injured')) I(a, b, c)) SELECT AggregateAccident.reportNumber, Injury.injuryCode, Injury.description, AggregateAccident.victimCount FROM (SELECT Accidents.reportNumber, MAX(Injury.severity) as severity, COUNT(*) as victimCount FROM Accidents JOIN Injury ON Injury.injuryCode = Accidents.injuryCode GROUP BY Accidents.reportNumber) AggregateAccident JOIN Injury ON Injury.severity = AggregateAccident.severity ORDER BY AggregateAccident.reportNumber ``` (And [updated SQL Fiddle](http://sqlfiddle.com/#!6/20e51/1)) The `WITH` clause constructs what's known as a Common Table Expression (CTE), and is basically an inline view or temporary table definition. This could also be done with a subquery, but as I reference `Injury` twice, using a CTE means I only have to write the contained information once (in cases where the CTE is the result of some other query, this may help performance, too). Most recent/current RDBMSs support this functionality (notably, MySQL does not), including DB2.
This is not an answer, but an attempt to improve your skills. If you stored the injury code as a number like this: ``` 0 = Not injured 1 = Slight 2 = Serious 3 = Fatal ``` Then you could use this clear and simple SQL: ``` select reportnumber, max(injurycode) as injurycode, count(*) as involved from accidents group by reportnumber ``` Here is a fiddle to illustrate it: <http://sqlfiddle.com/#!2/87faf/1>
SQL query to select multiple values
[ "", "sql", "db2", "case", "" ]
I know there are a lot similar questions. Actually I used [this](https://stackoverflow.com/questions/12526194/mysql-inner-join-select-only-one-row-from-second-table) and it works, but I can't figure out how to include records, which don't have match in second table. I use sample Northwind db on MS SQL Server. Using this Query: ``` SELECT Customers.CustomerID, Customers.CompanyName, Orders.OrderID, Orders.OrderDate FROM Customers LEFT OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID INNER JOIN ( SELECT CustomerID, MAX(OrderDate) maxDate FROM Orders GROUP BY CustomerID ) b ON Orders.CustomerID = b.CustomerID AND Orders.OrderDate = b.maxDate ORDER BY Orders.OrderDate ``` I get correct result, but missing records, which don't match. If I use LEFT OUTER JOIN instead INNER JOIN: ``` SELECT Customers.CustomerID, Customers.CompanyName, Orders.OrderID, Orders.OrderDate FROM Customers LEFT OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID LEFT OUTER JOIN ( SELECT CustomerID, MAX(OrderDate) maxDate FROM Orders GROUP BY CustomerID ) b ON Orders.CustomerID = b.CustomerID AND Orders.OrderDate = b.maxDate ORDER BY Orders.OrderDate ``` I get missing records, but in this case I have repeated customer names. I want: get list of customers with only his last order and if he doesn't have order his name should be present anyway.
You got repeated customer names, because you link over orderdate. So if you have two or more orders on the last date for some customer you get all these last orders. If I assume that the orderid has the same sequence as the orderdate, following statement should return only one line for each customer. ``` select cs.*, o.* from customers cs left outer join ( select customerid, max(orderid) as orderid from orders group by customerid ) lnk on cs.customerid = lnk.customerid left outer join orders o on lnk.orderid = o.orderid order by cs.customerid ```
Best way to do this would be CTE with `ROW_NUMBER()` this query will have better cost because you hit `Orders` table only once instead of twice to get the data and once to get max record. ``` WITH LastOrder AS ( SELECT CustomerID ,OrderID ,OrderDate ,ROW_NUMBER() OVER ( PARTITION BY CustomerID ORDER BY OrderDate DESC ) AS RowNum FROM Orders) SELECT c.CustomerID ,c.CompanyName ,lo.OrderID ,lo.OrderDate FROM Customers AS c LEFT OUTER JOIN LastOrder AS lo ON c.Customer_id = lo.CustomerID AND lo.RowNum = 1 ```
join just last record in second table, but include records don't have match in second table
[ "", "sql", "sql-server", "join", "" ]
I need to find out the SUM of values in a column, which is like '$2' and the type is varchar. How can I convert this on the fly find the SUM ?
You are probably better off using MySQL's implicit conversion: ``` select sum(trim(replace(col, '$', '')) + 0.0) ``` The silent conversion will include cents. In addition, non-numeric characters are after the number will not cause an error. The `trim()` will remove leading spaces which could also affect conversion.
This will remove the first characters ans summarizes the remaining: ``` select sum(substring(field,2)) from table ```
SUM of amounts with Dollar sign
[ "", "mysql", "sql", "" ]
I have made two tables: one with 5 columns and the other with 3 columns. By using left outer join I want my resultant table to show all 5 columns of first table along with just first column of second table. any solution? It shows all 3 columns of second table but I want it to show just one.
`SELECT *` always shows *all* columns from all tables in the query. If you want a subset of these, you have to be more specific. Example: ``` SELECT t1.*, t2.column1 FROM t1 LEFT OUTER JOIN t2 ... ```
``` SELECT T1.*, T2.FirstColumnName FROM T1 LEFT OUTER JOIN T2 ON T1.Id = T2.Id ```
left outer join sql 2012
[ "", "sql", "" ]
What I am trying to do is something like this ``` INSERT INTO BOOKS(borrower_name,isbn) VALUES("Jane",SELECT isbn from TABLE...); ``` This is wrong obviously. But I am trying to get something that would work the way this would (if it did).
You were **very** close ``` INSERT INTO books (borrower_name, isbn) SELECT 'Jane', isbn FROM table_name -- WHERE id = ? ``` *You might want to limit number of rows coming from `table_name` by using `WHERE` clause and proper condition(s)* Here is **[SQLFiddle](http://sqlfiddle.com/#!2/fc28e/1)** demo --- More over if you meant to return from `SELECT` **only a scalar value** (just one ISBN) then you were **correct** in the first place and could've used syntax showed in your question ``` INSERT INTO books (borrower_name,isbn) VALUES ('Jane', ( SELECT isbn FROM table_name WHERE id = 1 )); ``` Here is **[SQLFiddle](http://sqlfiddle.com/#!2/88575/1)** demo
What you were doing is also right, u only missed `()` for select statement: ``` INSERT INTO BOOKS(borrower_name,isbn) VALUES("Jane",SELECT isbn from TABLE...); ``` should be modified to: ``` INSERT INTO BOOKS(borrower_name,isbn) VALUES("Jane",(SELECT isbn from TABLE...)); ``` and it will work perfectly fine!! here is the [SQLFiddle demo](http://sqlfiddle.com/#!2/d8fee/1)
How to insert into a table from another table and from user input?
[ "", "mysql", "sql", "" ]
Complicated SQL query needed here, not sure if it's even possible. I have a table like this: ``` ------------------------ |uid |lesson_id |score | ------------------------ |1 |0 |20 | |1 |0 |25 | |1 |0 |15 | |1 |0 |40 | |1 |1 |70 | |1 |0 |10 | |1 |1 |20 | |1 |1 |55 | |1 |1 |55 | |1 |0 |5 | |1 |2 |65 | ------------------------ ``` For a particular user, I need to get the maximum score for each lesson, sum them, then get their average... all in a single SQL query. Max scores: ``` ----------------------- |lesson_id |max_score | ----------------------- |0 |40 | |1 |70 | |2 |65 | ----------------------- ``` Sum: ``` ------ |sum | ------ |175 | ------ ``` Average: ``` ------- |avg | ------- |58.3 | ------- ``` How's this? ``` SELECT uid AS id, AVG(max_score) AS avg_score FROM ( SELECT uid, lesson_id, max(score) AS max_score FROM cdu_user_progress WHERE session_id = $session_id GROUP BY uid, lesson_id ) AS tt WHERE uid IN ($ids) GROUP BY uid ORDER BY avg_score ```
You can just use subqueries: ``` SELECT uid, SUM(MaxScore), Avg(MaxScore) FROM ( SELECT uid, lesson_id,max(score) as MaxScore FROM scores GROUP BY userid, lesson_id ) AS m GROUP BY uid ``` or for just one user: ``` SELECT SUM(MaxScore), Avg(MaxScore) FROM ( SELECT lesson_id,max(score) as MaxScore FROM scores WHERE uid = $uid GROUP BY lesson_id ) AS m ``` or for "a bunch of specific users": ``` $uidlist = (comma-delimited list of user ids) SELECT uid, SUM(MaxScore), Avg(MaxScore) FROM ( SELECT uid, lesson_id,max(score) AS MaxScore FROM scores WHERE FIND_IN_SET(uid, $uidlist) GROUP BY uid, lesson_id ) AS m GROUP BY uid ```
Here are a simple sample **[SQLFIDDLE](http://sqlfiddle.com/#!2/bf33c9/1)** ``` select Avg(tt.maxscores) from ( select lesson_id,max(score) as maxscores from t group by lesson_id ) as tt ```
MAX, SUM then AVG all in one SQL query?
[ "", "mysql", "sql", "database", "" ]
I am attempting to generate item cost history. Items have cost values that change over time. For easier reporting, I'm trying to generate output that has a cost value by item by week ending date. What I'm fighting with is outputting the most recent item cost value for a given week end date, since most of the time the eff\_dt dates will not line up with a week ending date (`tran_end_dt`). I have the following data (simplified): ``` create table Item( item_id int ) insert into Item values(1),(2),(3) create table DatesTable( tran_end_dt date ) insert into DatesTable values('2014-01-04'),('2014-01-11'),('2014-01-18'),('2014-01-25') create table ItemCostHist ( item_id int, eff_dt date, item_cost int ) insert into ItemCostHist values(1,'2014-01-01',1),(1,'2014-01-19',2),(2,'2014-01-05',1),(2,'2014-01-17',2),(3,'2014-01-01',1),(3,'2014-01-08',2),(3,'2014-01-22',3) ``` This should give: Item ``` item_id 1 2 3 ``` DatesTable (Looking at End week/Saturdays only) ``` tran_end_dt 2014-01-04 2014-01-11 2014-01-18 2014-01-25 ``` ItemCostHist ``` item_id eff_dt item_cost 1 2014-01-01 1 1 2014-01-19 2 2 2014-01-04 1 2 2014-01-17 2 3 2014-01-01 1 3 2014-01-08 2 3 2014-01-22 3 ``` For the sake of keeping the post clean, I won't clutter it with a bunch of failed SQL attempts. What I've been trying to do, is cross join `Item` and `DatesTable` as an inline view to give each week ending date and item\_id, and then join this set against the `ItemCostHist` data. I keep running into trouble when attempting to get the `item_cost` value with an `eff_dt` that is less than or equal to the `tran_end_dt`. *I could solve this iteratively, but I'd like advice or examples on how to solve this with a set based approach.* Desired output: ``` Item tran_end_dt Item Cost 1 2014-01-04 1 1 2014-01-11 1 1 2014-01-18 1 1 2014-01-25 2 2 2014-01-04 1 2 2014-01-11 2 2 2014-01-18 2 2 2014-01-25 2 3 2014-01-04 1 3 2014-01-11 2 3 2014-01-18 2 3 2014-01-25 3 ```
I'm not sure if this is the best way to do it, but this gets me the result I want. ``` select item_id , tran_end_dt , cost from (select distinct item_id, tran_end_dt from item cross join datestable) a outer apply (select top 1 item_cost as cost from itemcosthist ich where ich.eff_dt <= a.tran_end_dt and ich.item_id = a.item_id order by eff_dt desc) b order by item_id, tran_end_dt, cost ```
See this I think I have here what you are looking , but not too sure why you would like to do so anyway heres my solution ``` SELECT item_id ,eff_dt ,item_cost FROM ItemCostHist UNION SELECT item_id ,DATEADD(dd, 7-(DATEPART(dw, eff_dt)), eff_dt) [WeekEnd] ,item_cost FROM ItemCostHist ``` **Result Set** ``` ╔═════════╦════════════╦═══════════╗ ║ item_id ║ eff_dt ║ item_cost ║ ╠═════════╬════════════╬═══════════╣ ║ 1 ║ 2014-01-01 ║ 1 ║ ║ 1 ║ 2014-01-04 ║ 1 ║ ║ 1 ║ 2014-01-19 ║ 2 ║ ║ 1 ║ 2014-01-25 ║ 2 ║ ║ 2 ║ 2014-01-04 ║ 1 ║ ║ 2 ║ 2014-01-17 ║ 2 ║ ║ 2 ║ 2014-01-18 ║ 2 ║ ║ 3 ║ 2014-01-01 ║ 1 ║ ║ 3 ║ 2014-01-04 ║ 1 ║ ║ 3 ║ 2014-01-08 ║ 2 ║ ║ 3 ║ 2014-01-11 ║ 2 ║ ║ 3 ║ 2014-01-22 ║ 3 ║ ║ 3 ║ 2014-01-25 ║ 3 ║ ╚═════════╩════════════╩═══════════╝ ```
Most recent cost value as of date by item
[ "", "sql", "sql-server", "t-sql", "sql-server-2012", "" ]
I have a list of data that I would like to order descending but i would like to start out with numbers then go to strings. Example of what I'm looking for. ``` 43a 34a 22a 11d ztc xtc ytc ``` but if you just do ``` SELECT list FROM table ORDER BY list DESC; ``` It outputs the list like this. ``` ztc xtc ytc 43a 34a 22a 11d ``` Is there a way to do this?
**Test table** ``` CREATE TABLE Data (str varchar(3)) INSERT INTO Data SELECT '43a' UNION SELECT '34a' UNION SELECT '22a' UNION SELECT '11d' UNION SELECT 'ztc' UNION SELECT 'xtc' UNION SELECT 'ytc' ``` **TSQL** ``` SELECT str FROM DATA ORDER BY 1-ISNUMERIC(LEFT(str, 1)) , str DESC ``` [ISNUMERIC](http://technet.microsoft.com/en-us/library/ms186272%28v=sql.100%29.aspx) return 1 for a number, 0 for non-number, so if u sort by `1-ISNUMERIC` first - numbers appear first. After that you can sort by field DESC **Demo: <http://sqlfiddle.com/#!3/e92a08/6>**
Something like this: ``` ;WITH CTE AS ( SELECT A FROM (VALUES('ztc'), ('xtc'), ('ytc'),('43a'),('34a'),('22a'),('11d')) T(A) ) SELECT * FROM CTE ORDER BY Left(A, PATINDEX('%[a-Z]%', A) - 1) DESC ```
How do you order a list by numbers then by strings descending?
[ "", "sql", "sql-server", "" ]
I have the following table ``` product_id product_name image_path misc ---------- -------------- ------------ ------ 1 flex http://firstpl... {"course_level_id":19,"group_id":"40067"} 2 Android http://firstpl... {"course_level_id":20,"group_id":"40072"} ``` So how can i retrieve the product\_name,image\_path & only "group\_id" value like "40067" from "misc" column. I tried below query but it returning 1/0 in Misc column. ``` SELECT product_name,image_path,misc REGEXP '(.*\"group_id\":*)' as Misc FROM ref_products where product_id=1 ``` Any idea guys how to do it ?
The `REGEXP` function just returns 0 or 1. You will have to use other string functions. Try this: `substr(misc,locate('group_id',misc)+11,5) as Misc`. But that assumes that group\_id always has 5 characters. So this is better: `substring_index(substr(misc,locate('group_id',misc)+char_length('group_id')+3),'"',1) as Misc`. Here is a fiddle to show it working: <http://sqlfiddle.com/#!2/ea02e/15> **EDIT** You can get rid of the `+3` magic number by including the double quotes and colon in the strings like this: `substring_index(substr(misc,locate('"group_id":"',misc)+char_length('"group_id":"')),'"',1) as Misc`
Since this question was asked MySQL have introduced support for the JSON data type. In MySQL 5.7.8 (and up) you can query the actual JSON string stored in the column using `JSON_EXTRACT()` or the equivalent `->` alias. EG: ``` SELECT product_name, image_path, JSON_EXTRACT(misc,'$.group_id') AS `group_id` FROM ref_products WHERE product_id=1 ``` See: <https://dev.mysql.com/doc/refman/5.7/en/json.html>
How to retrieve values stored in JSON array in MySQL query itself?
[ "", "mysql", "sql", "json", "" ]
I have the following table. city, state, and zipcode are all varchar type and can be NULL. ``` MyContacts -id (int PK) -city (varchar null) -state (varchar null) -zipcode (varchar null) ``` I would like to return city, state, and zipcode formatted as a single value as follows: ``` Seattle WA 98423 if all are not NULL Seattle WA if zip is NULL Seattle 98423 if state is NULL WA 98423 if city is NULL Seattle if state and zip is NULL WA if city and zip is NULL 98423 if city and state is NULL NULL if all of them are NULL ``` I have been trying something like the following, but think I am going about it wrong. Thanks ``` SELECT COALESCE(CONCAT(city," ",state," ",zipcode),CONCAT(city," ",states),zipcode) AS location ```
``` CASE WHEN COALESCE(city,state,zip_code) IS NOT NULL THEN TRIM(REPLACE(CONCAT(IFNULL(city,""), " ", IFNULL(state,""), " ", IFNULL(zip code,"")), " "," ")) ELSE NULL END ``` OR `CONCAT_WS` already handles NULL effectively, so we don't need a NULL check inside it. ``` CASE WHEN COALESCE(city,state,zip_code) IS NOT NULL THEN CONCAT_WS(' ',city, state, zipcode) ELSE NULL END AS location ```
Maybe this? ``` SELECT CONCAT_WS(' ',COALESCE(city,''),COALESCE(state,''),COALESCE(zipcode,'')) AS location ```
Using SQL concat and coalesce to display when values are null
[ "", "mysql", "sql", "concatenation", "coalesce", "" ]
Iam trying to use group by statement but it gives me this error :- Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause But I need to group them accordind to their Feeid. ``` select st.ID,af.Fee_Head_Name,SUM(Amount) as tamt from admission af join student st on af.ID= FeeID group by FeeID ``` Without SUM(Amount)(means simply Amount) and Group by statement iam getting output like this: ``` Fee_Head_Name | Amount Admission | 5000 Tution | 2500 Games | 1500 Tution | 2500 Games | 1500 ``` But my desired must look Like this :- ``` Fee_Head_Name | Amount Admission | 5000 Tution | 5000 Games | 3000 ``` Please help me on this iam stuck here for so long and used almost everything but nothing work
Try like this ``` SELECT Fee_Head_Name , SUM(Amount) FROM TABLE1 GROUP BY Fee_Head_Name ``` # [GROUP BY](http://technet.microsoft.com/en-us/library/ms177673.aspx) **EDIT** IF you want to select ID also then use this ``` SELECT MIN(ID),Fee_Head_Name , SUM(Amount) FROM TABLE1 GROUP BY Fee_Head_Name ```
``` select af.Fee_Head_Name,SUM(Amount) as tamt from admission af join student st on af.ID= FeeID group by af.Fee_Head_Name ``` group by with column in your select statement
How to use Group By statement
[ "", "sql", "sql-server", "sql-server-2008", "t-sql", "group-by", "" ]
I am building a web application with cakephp 2.4 and I have firstly designed my users table with an integer auto-incrementing id, than since my urls are structured as : `http://mywebsite/users/view/username` I realized that instead of using an integer auto-increment, it may be better for performance to use username(VARCHAR 100) as my primary key.Now I am curious how would this approach affect site performance when the database grows.
As per other answers, use an integer for your PK. Pick the correct int size depending on how many records you're expecting. Not using an integer PK with Cake might cause some problems. if you're using a Framework, stick with it's conventions - that's the advantage of a framework! DO NOT generate a unique route for every user dynamically in your routes.php. That goes against the entire point of having generic routing. One route should account for this, and you deal with it in the relevant controller. For example, if you specify all of your real controllers/actions: ``` Router::connect('/:controller', array('controller' => 'user|anotherController|etc')); Router::connect('/:action', array('controller' => 'something'), array('action' => 'allowed|actions|etc')); Router::connect('/:action', array('controller' => 'else'), array('action' => 'allowed|actions|etc')); ``` You can then send everything else, as in, site.com/username, to somewhere specific. ``` Router::connect('/:username', array('controller' => 'users'), array('action' => 'view'), array('pass'=>array('username'), 'username' => 'regex')); ``` And accept the 'username' var in the view function, and use that to find the correct user from your db. Also, note that if
Don't use varchars as your primary key. It's horrible for performance, you need to explicitly check that you don't have duplicate keys, it's not conventional, foreign keys then need to be varchar, the router won't handle it properly... ugh. If you're worried about SEO, then you can read up on how [the cakePHP router can handle this](http://book.cakephp.org/2.0/en/development/routing.html). In my application I dynamically generate a routes file with the seo url that is matched to the ID of the thing that I'm trying to display. In your case this file would have entries like: ``` Router::connect('/users/view/johndoe', array( 'controller' => 'users', 'action' => 'view', 13)); ``` This solution works very well for me, and the seo portions are handled by an SEO behavior that is attached to the model. It also works with reverse routing, so that when you make a link like this: ``` <?php echo $this->Html->link(__('View'), array('action' => 'view', $user['User']['id'])); ?> ``` it will automatically create a link like /users/view/johndoe. If you decide to change this structure later on, or have a special user with a special path (like <http://mywebsite.com/user-john-connor>) then this will automatically change all links to that user's view to the new URL.
cakephp mysql ,autoincrement id or varchar as primary key
[ "", "mysql", "sql", "cakephp", "" ]
I have a small difficulty with writing a query: I have following table: ``` ID | FromId | ToId -------------------------- 1 10 15 2 10 15 3 15 10 4 15 10 5 15 20 6 14 15 7 20 15 8 20 10 9 10 20 10 10 1 ``` No i would like to get from here unique wich has value of 10 And by unique i mean for example, the result which i would like to accomplish, if the variable is 10 ``` FromId | ToId ------------------ 10 15 20 10 10 1 ``` I'm ofcourse not sure if it is possible to accomplish something like that tho ... For me in this case ``` 10 20 == 20 10 ``` But for sql not :/ I think ppl dont understand me completly... I need uniqueness in the combination with 10
You can do this as: ``` select least(fromId, toId) as fromId, greatest(fromId, toId) as toId from MyTable t where fromId = 10 or toId = 10 group by least(fromId, toId), greatest(fromId, toId); ``` EDIT: (In response to your question about performance.) You should have indexes on `fromId` and `toId`. Your original data has duplicate values, so the duplicates have to be removed. In MySQL, this requires sorting the data, either through an explicit `order by` or by using `group by` (and the associated filesort). The above query should perform as well as any query that uses `distinct`. If you have two indexes, on `t(fromId, toId)` and `t(toId, fromId)` then the following *might* perform better: ``` select distinct fromId, toId from MyTable t where fromId = 10 union all select distinct fromId, toId from MyTable t where toId = 10 and not exists (select 1 from MyTable t2 where t2.fromId = t.fromId and t2.toId = t.fromId); ``` MySQL can perform the `distinct` by scanning the index. I'm not sure if it does in practice.
I think this should work, ``` SELECT * FROM myTable WHERE FromId = 10 OR ToId = 10; ```
MySql select multiple column unique row
[ "", "mysql", "sql", "distinct", "" ]
I am trying to format a Vertica date column into only the month. I would need the final value in some sort of date datatype so in the report I can order the results by date/time, not order by text. So that February sorts after January etc. ``` select TO_DATE(TO_CHAR(purchase_date), 'Month') from transactions order by 1; ``` I am also tried: ``` select TO_DATE(TO_CHAR(MONTH(purchase_date)), 'Month') from transactions order by 1; ``` The above statements produce an error "Invalid value for Month" Any ideas?
How about this? ``` select to_char(purchase_date, 'Month') from transactions order by purchase_date; ``` You can order by columns that are not in the `select` list. EDIT: If you want to combine months from multiple years, the above will not work quite right. This will: ``` select to_char(purchase_date, 'Month') from transactions order by extract(month from purchase_date); ```
``` Select TO_CHAR((NOW() - INTERVALYM '1 MONTH'), 'MON'); ``` Output: ``` JUN ``` This will help you get only the name of the previous month.
How to format a Vertica date column into just the month?
[ "", "sql", "vertica", "" ]
``` select COUNT(DISTINCT devices) AS "Devices" from measure_tab where measure_tab.time >= 1375243200 and measure_tab.time < 1375315200; ``` The output of the above sql query gives a table with a column named "Devices" with number of devices. I want the time which is one of the attributes of measure\_tab should also get displayed in another column of the output table with the UNIX TIME which is 1375243200 in this query converted into the SQL datetime format which is `Thu Aug 1 00:00:00 UTC 2013`. Can someone help me out? Thanks
You can use function as below: ``` select FROM_UNIXTIME(UNIX_TIMESTAMP(),'%a %b %d %H:%i:%s UTC %Y'); ``` output will be: ``` 'Wed Feb 05 05:36:16 UTC 2014' ``` In your query ``` select COUNT(DISTINCT devices) AS "Devices", FROM_UNIXTIME(measure_tab.time,'%a %b %d %H:%i:%s UTC %Y') as d from measure_tab where measure_tab.time >= 1375243200 and measure_tab.time < 1375315200; ``` For more info you can check documentation: <http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime> You can see sql fiddle:<http://sqlfiddle.com/#!2/a2581/20357>
In Mysql you can use [from\_unixtime()](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime) function to convert unix timestamp to `Date`: ``` select COUNT(DISTINCT devices) AS "Devices" from measure_tab where measure_tab.time >= from_unixtime(1375243200) and measure_tab.time < from_unixtime(1375315200); ```
How to convert the UNIX TIME into SQL datetime format
[ "", "mysql", "sql", "datetime", "timestamp", "" ]
I am trying to write a query that will produce the top row and bottom row in one query. I can find one or the other but I cant get both in one row. Here is what I have: ``` SELECT (SELECT top(1) Lastname + ',' + firstname FROM CUSTOMERS join orders on customerID = customerID_fk join orderDetails on orderID = orderID_fk group by Lastname + ',' + firstname order by sum(quantity) desc); ``` Here is a link: <http://sqlfiddle.com/#!6/51ad4/129> What is the best practice to get the return I am looking for?
Here is one way using window functions: ``` select name from (SELECT Lastname + ',' + firstname as name, row_number() over (order by sum(quantity)) as rownum, count(*) over () as cnt FROM CUSTOMERS join orders on customerID = customerID_fk join orderDetails on orderID = orderID_fk group by Lastname + ',' + firstname ) t where rownum = 1 or rownum = cnt; ``` Here is another way: ``` with cte as ( SELECT Lastname + ',' + firstname as name, sum(quantity) as qty FROM CUSTOMERS join orders on customerID = customerID_fk join orderDetails on orderID = orderID_fk group by Lastname + ',' + firstname ) select top 1 name from cte order by qty union all select top 1 name from cte order by qty desc; ```
Possibly we can use sub query for this. The idea is to find out the Max and Minimum ordered items. Then we can use existing query and write something like sum(quantity) in (Sub Query Here). Or can you check if the following works? ``` SELECT (SELECT Top(2) Lastname + ',' + firstname FROM CUSTOMERS join orders on customerID = customerID_fk join orderDetails on orderID = orderID_fk group by Lastname + ',' + firstname order by sum(quantity) desc having sum(quantity) = Max(Sum(quantity)) or Sum(quantity)=Min(Sum(Quantity)) ```
How to return top and bottom row in one query?
[ "", "sql", "sql-server", "" ]
I'm going to use example tables. tblAnimal: ``` --------------------------------- |Animal | Colour | Gender | --------------------------------- |Dog | | | --------------------------------- ``` tblDescription: ``` ------------------------------- | Animal | ID | Description | ------------------------------- | Dog | 1 | Male | ------------------------------- | Dog | 92 | White | ------------------------------- ``` So I want to update tblAnimal so that the Colour and Gender are populated. I used the code ``` UPDATE tblAnimal SET Colour = CASE WHEN tblDescription.ID = 92 THEN tblDescription.Description END, Gender = CASE WHEN tblDescription.ID = 1 THEN tblDescription.Description END FROM tblDescription INNER JOIN tblAnimal ON tblDescription.Animal = tblAnimal.Animal ``` But it isn't working. Both columns in tblAnimal remains NULL. It seems like SQL Server only checks the first row in tblDescription. How would I write this UPDATE statement so that both Colour and Gender are what is in tblDescription? **EDIT** Thank you all for your solutions! And yes the table needs to be normalized, but this is strictly for example to go along with my question on the UPDATE statement. Thanks again everyone.
``` Create table tblDescription( Animal varchar(20), ID int, Description varchar(20) ) Insert into tblAnimal(Animal) values ('Dog') Insert into tblDescription Select 'Dog',1,'Male' union all Select 'Dog',92,'White' Select * from tblAnimal Select * from tblDescription ---Update Update a SET Colour = (Select d.description from tbldescription d where d.id =92), Gender = (Select d.description from tbldescription d where d.id =1) From tblAnimal a inner join tblDescription d on d.Animal =a.Animal ``` NOTE: This will work but what would i do is normalization of tbldescription.
Try this : ``` UPDATE tblAnimal a SET a.Colour = (SELECT d.Description d FROM tblDescription d WHERE d.Animal = a.Animal AND ID = 92), a.Gender = (SELECT d.Description d FROM tblDescription d WHERE d.Animal = a.Animal AND ID = 1) ```
SQL Update with CASE statement
[ "", "sql", "sql-server", "sql-update", "" ]
I have two queries, and I want to join the first query with the second in SQL, here are my queries, FIRST QUERY ``` OleDbCommand Query1 = new OleDbCommand(); Query.CommandText = "SELECT [Mastertable].ID " + "FROM [Mastertable] INNER JOIN [relationship] ON [Mastertable].ID = [relationship].SW1_ID " + "WHERE ([Mastertable].[PN]= @PN AND [Mastertable].[Ver]=@Ver) " + "GROUP BY [Mastertable].[ID]"; DataSet ResultSet = RunQuery(Query1); ``` The above query basic return the ID where PN = PN input and Ver = Version input.( I put the result in a Dataset I want to join the ID column from query1 to Mastertable. ID again the 2nd query, ``` OleDbCommand Query2 = new OleDbCommand(); Query2.CommandText = "SELECT [Mastertable].PN, [Mastertable].[Ver], [relationship].[Category], [Mastertable].[Component_Name] " + "FROM (Query1 INNER JOIN [relationship] ON Query1.[ID] = [relationship].SID) INNER JOIN " + "[Mastertable] ON [relationship].SW2_ID = [Mastertable].[ID]"; DataSet ResultSet2 = RunQuery(Query2); ``` but this code doesn't work, I searched on the web alot and tried a few, but they didn't help. I was thinking to use the ResultSet1.Tables[0].TableName and ResultSet1.Tables[0].Columns[0].Name, but that didn't work =( Please help
``` OleDbCommand Query2 = new OleDbCommand(); Query2.CommandText = "SELECT [SW Mastertable].SW_PN, [SW Mastertable].[SW_Ver], [SW relationship].[SW2_Category]," + " [SW Mastertable].[Component_Name] " + " FROM " + "(SELECT [Mastertable].ID as ID " + "FROM [Mastertable] INNER JOIN [relationship] ON [Mastertable].ID = [relationship].SW1_ID " + "WHERE ([Mastertable].[PN]= @PN AND [Mastertable].[Ver]=@Ver) " + "GROUP BY [Mastertable].[ID]) as Query1 " + " INNER JOIN [SW relationship] ON Query1.[ID] = [SW relationship].SW1_ID INNER JOIN " + "[SW Mastertable] ON [SW relationship].SW2_ID = [SW Mastertable].[ID]"; DataSet ResultSet2 = RunQuery(Query2); ```
You can join Query1 to the second (outer) Query2 as a derived table as follows: ``` SELECT [SW Mastertable].SW_PN, [SW Mastertable].[SW_Ver], [SW relationship].[SW2_Category], [SW Mastertable].[Component_Name] FROM (SELECT [Mastertable].ID FROM [Mastertable] INNER JOIN [relationship] ON [Mastertable].ID = [relationship].SW1_ID WHERE ([Mastertable].[PN]= @PN AND [Mastertable].[Ver]=@Ver) GROUP BY [Mastertable].[ID] ) Query1 INNER JOIN [SW relationship] ON Query1.[ID] = [SW relationship].SW1_ID) INNER JOIN [SW Mastertable] ON [SW relationship].SW2_ID = [SW Mastertable].[ID]; ``` If you are using `sql-server` you can also do this with a CTE: ``` WITH Query1 AS ( SELECT [Mastertable].ID FROM [Mastertable] INNER JOIN [relationship] ON [Mastertable].ID = [relationship].SW1_ID WHERE ([Mastertable].[PN]= @PN AND [Mastertable].[Ver]=@Ver) GROUP BY [Mastertable].[ID] ) SELECT [SW Mastertable].SW_PN, [SW Mastertable].[SW_Ver], [SW relationship].[SW2_Category], [SW Mastertable].[Component_Name] FROM Query1 INNER JOIN [SW relationship] ON Query1.[ID] = [SW relationship].SW1_ID) INNER JOIN [SW Mastertable] ON [SW relationship].SW2_ID = [SW Mastertable].[ID]; ```
How to Join a query to another query
[ "", "asp.net", "sql", "" ]
I have 2 tables A and B. Table A contains **names** and table B contains **selected names**. Now I would like to perform the following query on these tables using greendao, Please let me know if it is possible and if it is not are there any alternatives (maybe a raw query). ``` select * from A inner join B on A.nameid = B.nameid ``` Also, Table A columns: `id, nameid, name` and Table B columns: `id, nameid, name, rating`
I think this might help. You can use the raw query as a fake join. And you get all you want in the Query object ``` Query query = ATableDao.queryBuilder().where( new StringCondition("nameid IN " + "(SELECT nameid FROM B_Table )").build(); ``` Since "nameid" doesn't seems to be a unique identifier in your sample. I won't suggest to use Relations to solve this issue. If you are try to use [Relations](http://greendao-orm.com/documentation/relations/), you can find my previous answer [here.](https://stackoverflow.com/questions/21215668/greendao-store-list-of-entities-in-other-entity/21230885#21230885)
Try this: ``` List<ATableObj> listATableObj = ATableDao.queryRawCreate(", BTable BT WHERE BT.nameid = T.nameid").list(); ```
How to Perform the following query using Greendao ?
[ "", "android", "sql", "greendao", "" ]
Iam getting the error ``` #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ID' int, 'MGR_ID' int, 'DEPT_ID' int, 'NAME' VARCHAR2(30), 'SAL' int, ' at line 3 while creating a table. I have already a table department with PK as 'dept_id'. Help lease CREATE TABLE emp ( 'ID' int, 'MGR_ID' int, 'DEPT_ID' int, 'NAME' VARCHAR2(30), 'SAL' int, 'DOJ' DATE, PRIMARY KEY ('ID') , FOREIGN KEY ('MGR_ID') REFERENCES emp('ID') , FOREIGN KEY ('DEPT_ID') REFERENCES department('dept_id') ) ```
Use back ticks ( ` ) to define object names, but not single quotes ( ' ). Your table definition shall be: ``` CREATE TABLE emp ( `ID` int, `MGR_ID` int, `DEPT_ID` int, `NAME` VARCHAR2(30), `SAL` int, `DOJ` DATE, PRIMARY KEY (`ID`) , FOREIGN KEY (`MGR_ID`) REFERENCES emp(`ID`) , FOREIGN KEY (`DEPT_ID`) REFERENCES department(`dept_id`) ) ```
Don't quote your field names with `'`. That turns them into strings, not field names. ``` CREATE TABLE emp ( id int, mgr_id int, etc... ); ``` If you **DO** need to quote a field name because it's a reserved word, you use backticks: ``` CREATE TABLE emp ( `desc` int <---"desc" is a reserved word etc... ); ```
1064 sql error in create table statement
[ "", "mysql", "sql", "" ]
I am running a `SELECT INTO` statement like this so I can manipulate the data before finally dropping the table. ``` SELECT colA, colB, colC INTO #preop FROM tblRANDOM ``` However when I run the statement and then, without dropping the newly created table, I then run either of the following statements, the table isn't found? Even scanning through object explorer I can't see it. Where should I be looking? ``` SELECT [name] FROM sysobjects WHERE [name] = N'#preop' SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '#preop' ```
Temp tables aren't stored in the local database, they're stored in `tempdb`. Also their name isn't what you named them; it has a hex code suffix and a bunch of underscores to disambiguate between sessions. And you should use [`sys.objects`](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2005/ms190324(v=sql.90)?redirectedfrom=MSDN) or [`sys.tables`](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2005/ms187406(v=sql.90)?redirectedfrom=MSDN), not the [deprecated `sysobjects` (note the big warning at the top)](https://learn.microsoft.com/en-us/sql/relational-databases/system-compatibility-views/sys-sysobjects-transact-sql?redirectedfrom=MSDN&view=sql-server-ver16) or [the incomplete and stale `INFORMATION_SCHEMA` views](https://sqlblog.org/2011/11/03/the-case-against-information_schema-views). The following query will show that if you have multiple sessions with the same #temp table name (`#preop`), they show up in the metadata with distinct names, and the name is not just `#preop`. To be crystal clear, this is not how to find the `object_id` for this specific #temp table in your session, it will also return others. Again, to avoid any confusion, I never intended anyone to expect this is a safe query for finding a #temp table in your session named `#preop`. It is merely demonstrating why there isn't a table named `#preop` in `tempdb.sys.objects`: ``` SELECT name FROM tempdb.sys.objects WHERE name LIKE N'#preop[_]%'; ``` If you are trying to determine if such an object exists *in your session*, so that you know if you should drop it first, you should do: ``` IF OBJECT_ID('tempdb.dbo.#preop') IS NOT NULL BEGIN DROP TABLE #preop; END ``` In modern versions (SQL Server 2016+), this is even easier: ``` DROP TABLE IF EXISTS #preop; ``` However if this code is in a stored procedure then there really isn't any need to do that... the table should be dropped automatically when the stored procedure goes out of scope.
I'd prefer to query `tempdb` in such manner: ``` IF EXISTS (SELECT * FROM tempdb.sys.objects WHERE object_id = OBJECT_ID(N'tempdb.[dbo].[#MyProcedure]') AND type in (N'P', N'PC')) BEGIN print 'dropping [dbo].[#MyProcedure]' DROP PROCEDURE [dbo].[#MyProcedure] END GO ```
Finding #temp table in sysobjects / INFORMATION_SCHEMA
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I have the following SQL that creates the table below: ``` SELECT c.cOLUMN1 , c.cOLUMN2 , COALESCE (sc.cOLUMN3, 'XXX') AS cOLUMN3 FROM tabel AS c COLUMN1 COLUMN2 COLUMN3 1 1 XXX 1 1 26785 1 1 23432 1 1 XXX ``` I want to add two new columns - if the value in column3 is equal too 'XXX' then the new in **NEWCOLUMN\_A** should be '0' and **NEWCOLUM\_B** should be '1'. Otherwise the new in **NEWCOLUMN\_A** should be '1' and **NEWCOLUM\_B** should be '1'. As shown below: ``` COLUMN1 COLUMN2 COLUMN3 NEWCOLUMN_A NEWCOLUMN_B 1 1 XXX 0 1 1 1 26785 1 1 1 1 23432 1 1 1 1 XXX 0 1 ```
``` SELECT c.cOLUMN1 , c.cOLUMN2 , COALESCE (c.cOLUMN3, 'XXX') AS cOLUMN3, (CASE WHEN COALESCE(c.cOLUMN3, 'XXX') = 'XXX' THEN 0 ELSE 1 END) AS NEWCOLUMN_A, 1 AS NEWCOLUMN_B FROM tabel AS c ``` Alternatively, since column 3 is derived... ``` SELECT c.cOLUMN1 , c.cOLUMN2 , COALESCE (c.cOLUMN3, 'XXX') AS cOLUMN3, (CASE WHEN c.cOLUMN3 IS NULL THEN 0 ELSE 1 END) AS NEWCOLUMN_A, 1 AS NEWCOLUMN_B FROM tabel AS c ```
First add the columns to the table: ``` ALTER TABLE tabel ADD NEWCOLUMN_A BIT NULL; ALTER TABLE tabel ADD NEWCOLUMN_B BIT NULL; ``` then `UPDATE` the table: ``` UPDATE tabel SET NEWCOLUMN_A = CASE WHEN COLUMN3 = 'XXX' THEN 0 ELSE 1 END, NEWCOLUMN_B = 1 ```
Add new columns to exsiting table in view
[ "", "sql", "sql-server", "" ]
This is the Query I have written ``` Select C.CUST_NAME,P.PROD_DESCRIP from Customer C JOIN (Ord O,OrderItem OT, Product P) ON (C.CUST_ID = O.CUST_ID AND O.ORD_ID = OT.ORD_ID AND OT.PROD_ID = P.PROD_ID) GROUP BY C.CUST_NAME ORDER BY OT.ORDITEM_QTY DESC ``` But the issue is it giving me **Right Parenthesis** Missing issue
Although that join syntax is allowed in some databases, it is really much clearer to split out the joins: ``` Select C.CUST_NAME, P.PROD_DESCRIP from Customer C JOIN Ord O on C.CUST_ID = O.CUST_ID JOIN OrderItem OT on O.ORD_ID = OT.ORD_ID JOIN Product P ON OT.PROD_ID = P.PROD_ID GROUP BY C.CUST_NAME ORDER BY OT.ORDITEM_QTY DESC; ``` By the way, this probably isn't doing what you think it does. It is returning a customer name along with an arbitrary `prod_descrip`. It is then ordering this result by an arbitrary quantity -- perhaps from the same or a different row. If you want to get the customer name along with the product with the maximum quantity for that customer, you can do this: ``` Select C.CUST_NAME, substring_index(group_concat(P.PROD_DESCRIP order by OT.ORDITEM_QTY desc), ',', 1) as PROD_DESCRIP from Customer C JOIN Ord O on C.CUST_ID = O.CUST_ID JOIN OrderItem OT on O.ORD_ID = OT.ORD_ID JOIN Product P ON OT.PROD_ID = P.PROD_ID GROUP BY C.CUST_NAME; ``` Note: If `PROD_DESCRIP` could have a comma then you will want to use a different separator character. EDIT: The above is the MySQL solution. In Oracle, you would do: ``` select CUST_NAME, PROD_DESCRIP from (Select C.CUST_NAME, P.PROD_DESCRIP, row_number() over (partition by C.CUST_NAME order by OT.ORDITEM_QTY desc) as seqnum from Customer C JOIN Ord O on C.CUST_ID = O.CUST_ID JOIN OrderItem OT on O.ORD_ID = OT.ORD_ID JOIN Product P ON OT.PROD_ID = P.PROD_ID ) t where seqnum = 1; ``` This is actually the preferred standard SQL solution. It will work in most databases (SQL Server, Oracle, Postgres, DB2, and Teradata).
``` SELECT C.CUST_NAME, P.PROD_DESCRIP FROM Customer C INNER JOIN Ord O ON C.CUST_ID = O.CUST_ID INNER JOIN OrderItem OT ON O.ORD_ID = OT.ORD_ID INNER JOIN Product P ON OT.PROD_ID = P.PROD_ID GROUP BY C.CUST_NAME ORDER BY OT.ORDITEM_QTY DESC ```
Missing Right Parenthesis issue
[ "", "sql", "" ]
Say I run the following query on psql: ``` > select a.c1, b.c2 into temp_table from db.A as a inner join db.B as b > on a.x = b.x limit 10; ``` I get the following message: > NOTICE: Table doesn't have 'DISTRIBUTED BY' clause -- Using > column(s) named 'c1' as the Greenplum Database data distribution key > for this table. > HINT: The 'DISTRIBUTED BY' clause determines the > distribution of data. Make sure column(s) chosen are the optimal > data distribution key to minimize skew. 1. What is a `DISTRIBUTED BY` column? 2. Where is `temp_table` stored? Is it stored on my client or on the server?
1. DISTRIBUTED BY is how Greenplum determines which segment will store each row. Because Greenplum is an MPP database in most production databases you will have multiple segment servers. You want to make sure that the Distribution column is the column you will join on usaly. 2. temp\_table is a table that will be created for you on the Greenplum cluster. If you haven't set search\_path to something else it will be in the public schema.
For your first question, the `DISTRIBUTE BY` clause is used for telling the database server how to store the database on the disk. ([Create Table Documentation](http://postgres-xc.sourceforge.net/docs/0_9_7/sql-createtable.html)) I did see one thing right away that could be wrong with the syntax on your Join clause where you say `on a.x = s.x` --> there is no table referenced as s. Maybe your problem is as simple as changing this to `on a.x = b.x`? As far as where the temp table is stored, I believe it is generally stored on the database server. This would be a question for your DBA as it is a setup item when installing the database. You can always dump your data to a file on your computer and reload at a later time if you want to save your results (without printing.)
DISTRIBUTE BY notices in Greenplum
[ "", "sql", "greenplum", "" ]
A comma separated file contains two columns with two strings. ``` A, abc* A, abc.def.ghi A, abc.def.ghi.jkhl B, abc.def.gh B, cde.def.abc B, cde.def.* ``` The char \* is a wildcard matching zero or more. What is the simplest way to remove reduntant lines, i.e matches to any wildcard line? Preferably with Unix filters or SQL, but any non-gui solution is helpful. Expected output: ``` A, abc* B, abc.def.gh B, cde.def.* ```
Using awk ``` awk -F \* 'NR==FNR{if (/\*/)a[$1]} NR>FNR{ if (/\*/) {print;next} s=0 for (i in a) {if ($0~i){s++;break}} if (s==0) print }' file file ``` ### Explanation * `-F \*` Use \* as Field-Splitting * `if (/\*/)a[$1]` save $1 of the line with \* into array a, so get two : `A, abc` and `B, cde.def.` * The next part in `NR>FNR`, read the file again, if the line has \*, print directly. If not, calculate if the current line match `A, abc` or `B, cde.def.`. If finally s is still is 0, that means no match, print, otherwise, skip.
You could do this in SQL as: ``` select t.* from table t where not exists (select 1 from table t2 where t.col1 = t2.col1 and t.col2 like replace(t2.col2, '*', '%') and t.col2 <> t2.col2 ); ```
Filter data based on matches within data
[ "", "sql", "sed", "filter", "awk", "" ]
When using oracle SQL is it possible to run a query based on a text\_string from a subquery? An example might clarify what I'm trying to do ``` select count(sql_text), sql_text from (select sql_text from query_table) sql_table group by sql_text; ``` The outer query is intended to count the number of results for each query retrieved from the query\_table. Is there some way I can execute the sql statements I retrieved from my query\_table in the same query? Thanks EDIT: I was able to query sql from a table using the dbms\_xmlgen.get\_xml() function. I suppose that any command which caused the sql to be parsed and executed would work. That being said, here's the generic code that I was able to accomplish things with: ``` select to_number ( extractvalue( xmltype( dbms_xmlgen.getxml('select count(*) c from '|| table_name)), '/ROWSET/ROW/C'))counter, sql_text from (select '('||sql_text||')' table_name from query_table) sql_table; ``` While perhaps not the most elegant way to do things, it works and is a single sql statement.
Generally, this isn't a particularly good design-- storing SQL in tables and dynamically executing it introduces all sorts of security and maintenance issues. It is probably possible (though it's way too late on a Friday that started way too early for me to try to figure it out) to do a really cool XML query along the lines of [this query that runs a count(\*) against every table in the schema](http://laurentschneider.com/wordpress/2007/04/how-do-i-store-the-counts-of-all-tables.html) that would do this all in one query. For the vast majority of programmers, though, the simpler approach would be to loop over the queries, run them one at a time, and store the results somewhere. Potentially the local variable would be added to a collection of counts, for example. ``` FOR q IN (SELECT sql_text FROM query_table) LOOP EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM (' || q.sql_text || ')' INTO some_local_variable; <<do something with the local variable>> END LOOP; ``` Since you're trying to create a view, you could take this logic and put it in a pipelined table function. You'd do a `PIPE ROW` to return data within the loop. Your view could then be created on top of the pipelined table function.
Going through Basics.. When the database executes an `SQL` 1) It would first do `SEMANTIC` check by validating the *syntax* and the *objects* (tables and columns used) in SQL. 2) Based on it, the `optimizer` draws a `PLAN`(calculating the indexes to be used, with the available table statistics and histograms).. 3) And the `SQL Engine` executes the Query as per the *PLAN*. So, all these means, the SQL cannot do dynamic object referings.. Since it needs to study all the elements in SQL before execution itself. Hence, unfortunately, your requirement is *NOT* possible with a simple SQL solution. `PL/SQL` or some other Database specific special tools.. is what you have to opt for.
Can an oracle SQL query execute a string query selected from a table?
[ "", "sql", "oracle", "oracle11g", "" ]
I have a table that stores basic site information, another one that stores the site address, and a third table for the phone. My phone table contains phone numbers, and the type of number. What I want to do is get my site information, and the main contact number and fax number. So far, my statement looks like this: ``` SELECT site.isiteid, site.iclientid, csitecode, csitename, binactive, caddress1, caddress2, ccity, cstateid, czip, icountryid, cattention, cemail, cnumber, cextension FROM dbo.site INNER JOIN dbo.address ON dbo.site.isiteid = dbo.address.isiteid AND (site.isiteid = 2) LEFT JOIN dbo.phone ON dbo.site.isiteid = dbo.phone.isiteid AND (dbo.phone.iphtypeid = 1) ``` This gets me all of the information that I need except for the fax number (dbo.phone.iphtypeid=3). Is there a way to add another column to the result called [fax], and populate it when site.isiteid=phone.isiteid AND phone.iphtypeid=3? Thus, the last 4 columns returned would be `[cemail][cnumber][cextension][cfax].` **RESOLVED** Thank you to all three who answered. All the answers were similar, so I selected the one that had the most detailed explanation. I did need to add the table name to both cnumber references and cextension to avoid ambiguity. Thank you for the responses!
Yes, you can do this by adding another join to `dbo.phone`. To distinguish between the two uses, you will need to give the second join an alias. So, something like: ``` SELECT site.isiteid, site.iclientid, csitecode, csitename, binactive, caddress1, caddress2, ccity, cstateid, czip, icountryid, cattention, cemail, phone.cnumber, phone.cextension, phone_fax.cnumber AS cfax FROM dbo.site INNER JOIN dbo.address ON dbo.site.isiteid = dbo.address.isiteid AND (site.isiteid = 2) LEFT JOIN dbo.phone ON dbo.site.isiteid = dbo.phone.isiteid AND (dbo.phone.iphtypeid = 1) LEFT JOIN dbo.phone AS phone_fax ON dbo.site.isiteid = phone_fax.isiteid AND (phone_fax.iphtypeid = 3) ```
Add another `JOIN` clause ``` LEFT JOIN dbo.phone f ON dbo.site.isiteid = f.isiteid AND f.iphtypeid = 3 ``` You would then add f.cfax to the `SELECT` list. It might also be good to give the other tables aliases so you can distinguish which columns are coming from which tables.
SQL Query that sorts information into two new columns based on a third column
[ "", "sql", "sql-server", "sql-server-2008", "" ]
The tables are: ``` blogs blog_id, user_id, blog_content users user_id, user_name comments comment_id, blog_id, user_id, comment_content ``` What I'd like to do is get the: blog\_content, the user\_name of the person that created the blog, the comment\_content associated with the particular blog, and the user\_name of the writers of the comments. I have no idea how to get the last one, the user\_name of the comment writers. I have this so far: ``` SELECT blogs.user_id, blogs.blog_id, blogs.blog_content, users.user_id, users.name, comments.comment_id, comments.blog_id, comments.user_id, comments.comment_content FROM blogs LEFT JOIN users ON users.user_id = blogs.user_id LEFT JOIN comments ON comments.blog_id = blogs.blog_id WHERE blogs.blog_id = 2 ``` How can i also join the tables comments and users in this query, and get both the user\_name of the blog creator, and of the comments writers?
You can have multiple joins on the same table. Each join will retrieve another set of data from that table. In order to include the same table multiple times in a single query, you must create an [alias](http://www.w3schools.com/sql/sql_alias.asp) for at least one of the copies so that SQL knows which one you are referring to when attempting to retrieve data from their columns. Since you need to get the **username for the users who wrote the comments**, I would recommend joining again on the **users** table, as follows: ``` SELECT blogs.user_id, blogs.blog_id, blogs.blog_content, users.user_id, users.name, comments.comment_id, comments.blog_id, comments.user_id, comments.comment_content , comment_writers.name as CommentUserName FROM blogs LEFT JOIN users ON users.user_id = blogs.user_id LEFT JOIN comments ON comments.blog_id = blogs.blog_id LEFT JOIN users AS comment_writers ON comment_writers.user_id = comments.user_id WHERE blogs.blog_id = 2 ```
You need to join the comments table back to another copy of the users table: ``` SELECT b.user_id, b.blog_id, b.blog_content, u.user_id, u.name, c.comment_id, c.blog_id, c.user_id, c.comment_content , uc.name as commentor_name FROM blogs b LEFT JOIN users u ON u.user_id = b.user_id LEFT JOIN comments c ON c.blog_id = b.blog_id LEFT JOIN comments uc on c.user_id = uc.user_id WHERE b.blog_id = 2; ``` In this query, all the tables have table aliases. This helps make the query more readable. Also, the table aliases are needed to distinguish the two references to `users`. One reference is for the blog owner and the other is for the comment writer.
sql - joining 3 tables on same column
[ "", "mysql", "sql", "" ]
I have 2 columns from a table and i want to add a third column to output the result of a calculation select statement at the moment is: ``` select revenue, cost from costdata ``` my 2 columns are revenue and cost table name: costdata my formula is: `= ((revenue - cost)/ revenue)*100` I want the third column to be named 'result' any idea on how to do this in a select statement?
Query: ``` SELECT revenue, cost, CASE WHEN revenue <> 0 THEN ((revenue - cost) / revenue) * 100 ELSE 0 END As result FROM costdata ```
``` SELECT revenue , cost , ((revenue - cost) / revenue) * 100 As result FROM costdata ``` You mentioned in the comments that you get a divide by zero error. This wll occur when `revenue` equals zero. What you want to happen in this scenario is up to you but this should get you started ``` SELECT revenue , cost , CASE WHEN revenue = 0 THEN 0 ELSE ((revenue - cost) / revenue) * 100 END As result FROM costdata ```
Add a column into a select for calculation
[ "", "sql", "sql-server", "formula", "" ]
I have two tables named tblborrow and tblreturn wherein they both have date columns. Now, what I am trying to do is to display almost all my columns from both tblborrow and tblreturn, in order by their date\_borrowed and date\_returned in union. My tblborrow contains the following columns: * borrow\_id * isbn * member\_id * staff\_id * date\_borrowed While tblreturn contains: * return\_id * borrow\_id * staff\_id * date\_returned I have done displaying them with left join using this: ``` SELECT a.isbn, a.member_id, a.staff_id, a.date_borrowed, b.staff_id, b.date_returned FROM tblborrow AS a left join tblreturn AS b on a.borrow_id = b.borrow_id ORDER BY date_borrowed, date_returned ``` It has given me what I need except the date\_returned and date\_borrowed are displayed in separate columns, of course. Now I tried to use UNION on them by testing if it also gives me what I need and so I used: ``` SELECT date_borrowed FROM tblborrow UNION ALL SELECT date_returned FROM returning ``` And it has indeed. But I need these to be in one query only. I tried to simply combine the queries like this: ``` SELECT a.isbn, a.member_id, a.staff_id, b.staff_id, (SELECT date_borrowed FROM tblborrow UNION ALL SELECT date_returned FROM returning) FROM tblborrow AS a left join tblreturn AS b on a.borrow_id = b.borrow_id ORDER BY date_borrowed, date_returned ``` But it says "Subquery returns more than 1 row" and I still can't seem to do it after lots of thorough Google-ing. Help, anyone? Thanks in advance!
If you want to separate rows for a borrow/return combination, then `union all` is appropriate. If so, I think this does what you want: ``` SELECT b.isbn, b.member_id, b.staff_id, date_borrowed, 'borrow' as which FROM tblborrow b UNION ALL SELECT b.isbn, b.member_id, r.staff_id, date_returned, 'return' as which FROM tblreturn r join tblborrow b on r.borrw_id = b.borrow_id; ```
Try this by adding a join on your union set ``` SELECT a.isbn, a.member_id, a.staff_id, b.staff_id, u.combined_date FROM tblborrow AS a LEFT JOIN tblreturn AS b ON a.borrow_id = b.borrow_id LEFT JOIN (SELECT borrow_id, date_borrowed AS combined_date FROM tblborrow UNION ALL SELECT borrow_id, date_returned AS combined_date FROM returning) u ON (u.borrow_id = a.borrow_id) ORDER BY u.combined_date ```
MySQL: Using left join and union in one query
[ "", "mysql", "sql", "phpmyadmin", "" ]
Given the following example tables ``` TABLE_A ----- ID ----- 1 2 3 4 5 TABLE_B --------------------------- TABLE_A_ID DETAIL --------------------------- 1 val_x 2 val_x 2 val_y 4 val_y 5 val_other ``` I am doing a left join on these two tables and get the following output ``` ------------------------------- TABLE_A_ID DETAIL ------------------------------- 1 val_x 2 val_y 2 val_x 3 null 4 val_y 5 val_other ``` This is as I expect from a left join. The problem I have is that I also want to remove rows that have `DETAIL` = val\_y AND ALL rows that have a repeating `TABLE_A_ID` IF any row in the group has a `DETAIL` = val\_y So the output I need is; ``` ------------------------------- TABLE_A_ID DETAIL ------------------------------- 1 val_x 3 null 5 val_other ``` I have tried using `GROUP_BY TABLE_A_ID` and `HAVING DETAIL != val_y` but that doesn't seem to work. I think for obvious reasons as `GROUP_BY` and `HAVING` are for aggregates and eliminating values that are less than or greater than right? Is there a way to do this in MySQL or am I asking too much? Note: These are EXAMPLE tables. They do not reflect a production system, so would appreciate no comments or answers outside the scope of the question and example - it just confuses things.
You could use another `LEFT JOIN` to eliminate ids with a 'val\_y' value; ``` SELECT a.id as table_a_id, b1.detail FROM table_a a LEFT JOIN table_b b1 ON a.id = b1.table_a_id LEFT JOIN table_b b2 ON a.id = b2.table_a_id AND b2.detail = 'val_y' WHERE b2.detail IS NULL ``` [An SQLfiddle to test with](http://sqlfiddle.com/#!2/9348c/1) (updated with new sample data)
``` SELECT sub1.id table_a_id, sub1.detail FROM ( SELECT a.id, detail FROM table_a a LEFT JOIN table_b b on a.id = b.table_a_id) sub1 LEFT JOIN ( SELECT DISTINCT table_a_id FROM table_b WHERE detail = 'val_y') sub2 ON sub1.id = sub2.table_a_id WHERE sub2.table_a_id IS NULL ``` The `sub2` subquery finds all the IDs that meet your criteria for removal. This is then joined with the original query to filter out those IDs. [DEMO](http://www.sqlfiddle.com/#!2/0ecf5/1)
MySQL Join: Omit ALL repeating rows IF one row meets a condition
[ "", "mysql", "sql", "database", "join", "" ]
I have a huge (~500mb) SQL file that I need to run on my database. It is a data dump from a production database that I need to put into my development database. Normally, if it were smaller, I'd paste it into the SQL tab and run it, but that would definitely blow up my browser. If I import that SQL file into the development database, is is just like running the SQL file? Or is the import function specifically set to *import a whole* database?
You should try to import it from the console, so you do not depend on the file upload limitations: ``` C:> mysql -u root -p < file.sql ```
I can suggest two options that you can try: 1.I would say try BigDump. I had the exact same problem before. You can read and follow this article for more information: <http://moeamine.com/how-to-upload-a-big-sql-file-to-mysql> You can download big dump from the link below: <http://www.ozerov.de/bigdump/> 2.you can gzip or bzip the file and phpMyAdmin will decompress and run the script. Another option is to split the MYSQL file into number of files and load each of them individually.
How to Run Large SQL File in PHPMyAdmin
[ "", "mysql", "sql", "phpmyadmin", "" ]
I am returning multiple rows of a column as one single row and column: ``` SELECT STUFF(( SELECT '<br/>' + Notes FROM DailyTaskHours WHERE Notes IS NOT NULL AND Notes <> '' AND NonScrumStoryId = DTH.NonScrumStoryId FOR XML PATH('') ), 1, 1, '') ) ``` I want to insert line breaks between each row that is being concatenated in ASP.NET but my approach is not working: ![enter image description here](https://i.stack.imgur.com/gX99r.png) As you can see is being replaced by the database engine with `&lt;br /&gt;` How do I get the linebreaks in the database so it will render spaced on the webpage? Here is the entire control that I am working on for reference: ``` <asp:GridView CssClass="hoursGrid" ID="hoursReportGridView" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" DataSourceID="SqlDataSource2" OnRowDataBound="hoursReportGridView_OnRowDataBound" DataKeyNames="DifferentUsers, DoubleBookedFlag, PointPerson, Person"> <Columns> <asp:BoundField DataField="Person" HeaderText="Person" SortExpression="Project" /> <asp:BoundField DataField="Project" HeaderText="Project" SortExpression="Project" /> <asp:BoundField DataField="ProjectType" HeaderText="Project Type" ReadOnly="True" SortExpression="Sprint" ItemStyle-HorizontalAlign="Center" /> <asp:BoundField DataField="Theme" HeaderText="Theme" ReadOnly="True" SortExpression="Theme" ItemStyle-HorizontalAlign="Center" /> <asp:BoundField DataField="StoryNumber" HeaderText="Story Number" SortExpression="Story" ItemStyle-Width="6%" ItemStyle-HorizontalAlign="Center" /> <asp:BoundField DataField="StoryTitle" HeaderText="Story Title" SortExpression="Story" ItemStyle-Width="20%" /> <asp:BoundField DataField="Effort" HeaderText="Effort" SortExpression="Effort" ItemStyle-HorizontalAlign="Right" /> <asp:BoundField DataField="Task" HeaderText="Task" SortExpression="Task" ItemStyle-Width="20%" /> <asp:BoundField DataField="OriginalEstimateHours" HeaderText="Original Estimate" SortExpression="OriginalEstimateHours" ItemStyle-HorizontalAlign="Right" /> <asp:BoundField DataField="Monday" HeaderText="Mon" ReadOnly="True" SortExpression="Monday" ItemStyle-HorizontalAlign="Right" /> <asp:BoundField DataField="Tuesday" HeaderText="Tues" ReadOnly="True" SortExpression="Tuesday" ItemStyle-HorizontalAlign="Right" /> <asp:BoundField DataField="Wednesday" HeaderText="Wed" ReadOnly="True" SortExpression="Wednesday" ItemStyle-HorizontalAlign="Right" /> <asp:BoundField DataField="Thursday" HeaderText="Thurs" ReadOnly="True" SortExpression="Thursday" ItemStyle-HorizontalAlign="Right" /> <asp:BoundField DataField="Friday" HeaderText="Fri" ReadOnly="True" SortExpression="Friday" ItemStyle-HorizontalAlign="Right" /> <asp:BoundField DataField="Saturday" HeaderText="Sat" ReadOnly="True" SortExpression="Saturday" ItemStyle-HorizontalAlign="Right" /> <asp:BoundField DataField="Sunday" HeaderText="Sun" ReadOnly="True" SortExpression="Sunday" ItemStyle-HorizontalAlign="Right" /> <asp:TemplateField HeaderText="Total" ItemStyle-HorizontalAlign="Right"> <ItemTemplate> <asp:LinkButton ID="taskLinkButton" Text='<%# Eval("Total") %>' Enabled='<%# Eval("StoryTitle").ToString() != "" %>' runat="server" OnClick="taskLinkButton_Click" /> </ItemTemplate> </asp:TemplateField> </Columns> <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" /> <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" /> <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" /> <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" /> <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" /> <SortedAscendingCellStyle BackColor="#FFF1D4" /> <SortedAscendingHeaderStyle BackColor="#B95C30" /> <SortedDescendingCellStyle BackColor="#F1E5CE" /> <SortedDescendingHeaderStyle BackColor="#93451F" /> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>" SelectCommand=" SELECT RowType AS RowType ,Person AS Person ,Project AS Project ,ProjectType AS ProjectType ,Theme AS Theme ,StoryNumber AS StoryNumber ,StoryTitle AS StoryTitle ,Effort AS Effort ,Task AS Task ,OriginalEstimateHours AS OriginalEstimateHours ,MondayHours AS Monday ,TuesdayHours AS Tuesday ,WednesdayHours AS Wednesday ,ThursdayHours AS Thursday ,FridayHours AS Friday ,SaturdayHours AS Saturday ,SundayHours AS Sunday ,TotalHours AS Total ,DifferentUsers AS DifferentUsers ,DoubleBookedFlag AS DoubleBookedFlag ,PointPerson AS PointPerson FROM ( -- DATE DISPLAY SELECT '1' AS RowType ,'' AS Person ,'' AS Project ,'Category' AS ProjectType ,'' AS Theme ,'Ticket #' AS StoryNumber ,'' AS StoryTitle ,'' AS Effort ,'' AS Task ,'' AS OriginalEstimateHours ,'' AS Category ,'' AS IncidentNumber ,'' AS ApplicationName ,( CASE WHEN DATEDIFF(d, @startDateParam, @endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, @startDateParam, @endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 0, @startDateParam)) = 2 THEN CONVERT(VARCHAR(5), DATEADD(DAY, 0, @startDateParam), 101) ELSE '' END ) AS MondayHours ,( CASE WHEN DATEDIFF(d, @startDateParam, @endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, @startDateParam, @endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 1, @startDateParam)) = 3 THEN CONVERT(VARCHAR(5), DATEADD(DAY, 1, @startDateParam), 101) ELSE '' END ) AS TuesdayHours ,( CASE WHEN DATEDIFF(d, @startDateParam, @endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, @startDateParam, @endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 2, @startDateParam)) = 4 THEN CONVERT(VARCHAR(5), DATEADD(DAY, 2, @startDateParam), 101) ELSE '' END ) AS WednesdayHours ,( CASE WHEN DATEDIFF(d, @startDateParam, @endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, @startDateParam, @endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 3, @startDateParam)) = 5 THEN CONVERT(VARCHAR(5), DATEADD(DAY, 3, @startDateParam), 101) ELSE '' END ) AS ThursdayHours ,( CASE WHEN DATEDIFF(d, @startDateParam, @endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, @startDateParam, @endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 4, @startDateParam)) = 6 THEN CONVERT(VARCHAR(5), DATEADD(DAY, 4, @startDateParam), 101) ELSE '' END ) AS FridayHours ,( CASE WHEN DATEDIFF(d, @startDateParam, @endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, @startDateParam, @endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 5, @startDateParam)) = 7 THEN CONVERT(VARCHAR(5), DATEADD(DAY, 5, @startDateParam), 101) ELSE '' END ) AS SaturdayHours ,( CASE WHEN DATEDIFF(d, @startDateParam, @endDateParam) >= 7 THEN '' WHEN DATEDIFF(d, @startDateParam, @endDateParam) <= 5 THEN '' WHEN DATEPART(dw, DATEADD(DAY, 6, @startDateParam)) = 1 THEN CONVERT(VARCHAR(5), DATEADD(DAY, 6, @startDateParam), 101) ELSE '' END ) AS SundayHours ,'' AS TotalHours ,'' AS DifferentUsers ,'' AS DoubleBookedFlag ,'' AS PointPerson -- UNION ALL -- -- GRAND TOTALS -- SELECT '2' AS RowType ,'All Personnel' AS Person ,'' AS Project ,'' AS ProjectType ,'' AS Theme ,'' AS StoryNumber ,'' AS StoryTitle ,'' AS Effort ,'Total:' AS Task ,'' AS OriginalEstimateHours ,'' AS Category ,'' AS IncidentNumber ,'' AS ApplicationName ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 2 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Monday ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 3 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Tuesday ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 4 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Wednesday ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 5 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Thursday ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 6 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Friday ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 7 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Saturday ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 1 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS Sunday ,CAST(SUM(DTH.[Hours]) AS VARCHAR(20)) AS Total ,'' AS DifferentUsers ,'' AS DoubleBookedFlag ,'' AS PointPerson FROM DailyTaskHours DTH LEFT JOIN NonScrumStory NSS ON DTH.NonScrumStoryId = NSS.PK_NonScrumStory LEFT JOIN Task TSK ON DTH.TaskId = TSK.PK_Task LEFT JOIN Story STY ON TSK.StoryId = STY.PK_Story LEFT JOIN Product PDT ON STY.ProductId = PDT.PK_Product LEFT JOIN [User] USR ON DTH.EnteredBy = USR.DisplayName WHERE DTH.EnteredBy LIKE @userParam AND ActivityDate >= @startDateParam AND ActivityDate <= @endDateParam AND 1 = CASE ISNUMERIC(@productId) WHEN 0 THEN CASE WHEN DTH.TaskId IS NULL OR PDT.PK_Product LIKE @productId THEN 1 END WHEN 1 THEN CASE WHEN DTH.TaskId IS NOT NULL AND PDT.PK_Product = @productId THEN 1 END END AND ( ( @orgTeamPK = '%' AND ( USR.[OrganizationalTeamId] LIKE @orgTeamPK OR USR.[OrganizationalTeamId] IS NULL ) ) OR ( @orgTeamPK <> '%' AND (USR.[OrganizationalTeamId] LIKE @orgTeamPK) ) ) AND ( ( STY.Number LIKE @search OR STY.Number IS NULL ) OR ( STY.Title LIKE @search OR STY.Title IS NULL ) OR ( TSK.NAME LIKE @search OR TSK.NAME IS NULL ) ) AND ( ( @theme = '%' AND ( dbo.primaryTheme(STY.[Number]) LIKE @theme OR dbo.primaryTheme(STY.[Number]) IS NULL ) ) OR ( @theme != '%' AND dbo.primaryTheme(STY.[Number]) = @theme ) ) UNION ALL -- -- Details by PERSON, PROJECT, SPRINT, STORY, TASK -- SELECT '3' AS RowType ,DTH.EnteredBy AS Person ,COALESCE(PDT.[Name], APP.AppName) AS Project ,( CASE WHEN ( STY.KanBanProductId IS NOT NULL AND STY.SprintId IS NULL ) THEN 'Kanban' WHEN ( STY.KanBanProductId IS NULL AND STY.SprintId IS NOT NULL ) THEN 'Sprint' ELSE SCY.Catagory END ) AS ProjectType ,dbo.primaryTheme(STY.[Number]) AS Theme ,COALESCE(STY.[Number], NSS.IncidentNumber) AS StoryNumber ,COALESCE(STY.Title, NSS.[Description]) AS StoryTitle ,CONVERT(VARCHAR(20), STY.Effort) AS Effort ,COALESCE(TSK.[Name], ( SELECT STUFF(( SELECT ' | ' + Notes FROM DailyTaskHours WHERE Notes IS NOT NULL AND Notes <> '' AND NonScrumStoryId = DTH.NonScrumStoryId FOR XML PATH('') ), 1, 1, '') )) AS Task ,CONVERT(VARCHAR(20), TSK.OriginalEstimateHours) AS OriginalEstimateHours ,SCY.Catagory AS Category ,NSS.IncidentNumber AS IncidentNumber ,APP.AppName AS ApplicationName ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 2 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS MondayHours ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 3 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS TuesdayHours ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 4 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS WednesdayHours ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 5 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS ThursdayHours ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 6 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS FridayHours ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 7 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS SaturdayHours ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 1 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS SundayHours ,CAST(SUM(DTH.[Hours]) AS VARCHAR(20)) AS TotalHours ,CAST(SUM(CASE WHEN DTH.Hours > 0 THEN DTH.[UserDifference] END) AS VARCHAR(20)) AS DifferentUsers ,CAST(SUM(CASE WHEN DTH.Hours > 0 THEN DTH.DoubleBookedFlag END) AS VARCHAR(20)) AS DoubleBookedFlag ,DTH.PointPerson AS PointPerson FROM DailyTaskHours DTH LEFT JOIN Task TSK ON DTH.TaskId = TSK.PK_Task LEFT JOIN Story STY ON TSK.StoryId = STY.PK_Story LEFT JOIN NonScrumStory NSS ON DTH.NonScrumStoryId = NSS.PK_NonScrumStory LEFT JOIN SupportCatagory SCY ON NSS.CatagoryId = SCY.PK_SupportCatagory LEFT JOIN [Application] APP ON NSS.ApplicationId = APP.PK_Application LEFT JOIN Sprint SPT ON STY.SprintId = SPT.PK_Sprint LEFT JOIN Product PDT ON STY.ProductId = PDT.PK_Product LEFT JOIN [User] USR ON DTH.EnteredBy = USR.DisplayName WHERE DTH.EnteredBy LIKE @userParam AND ActivityDate >= @startDateParam AND ActivityDate <= @endDateParam AND 1 = CASE ISNUMERIC(@productId) WHEN 0 THEN CASE WHEN DTH.TaskId IS NULL OR PDT.PK_Product LIKE @productId THEN 1 END WHEN 1 THEN CASE WHEN DTH.TaskId IS NOT NULL AND PDT.PK_Product = @productId THEN 1 END END AND ( ( @orgTeamPK = '%' AND ( USR.[OrganizationalTeamId] LIKE @orgTeamPK OR USR.[OrganizationalTeamId] IS NULL ) ) OR ( @orgTeamPK <> '%' AND (USR.[OrganizationalTeamId] LIKE @orgTeamPK) ) ) AND ( ( STY.Number LIKE @search OR STY.Number IS NULL ) OR ( STY.Title LIKE @search OR STY.Title IS NULL ) OR ( TSK.NAME LIKE @search OR TSK.NAME IS NULL ) ) AND ( ( @theme = '%' AND ( dbo.primaryTheme(STY.[Number]) LIKE @theme OR dbo.primaryTheme(STY.[Number]) IS NULL ) ) OR ( @theme != '%' AND dbo.primaryTheme(STY.[Number]) = @theme ) ) GROUP BY DTH.EnteredBy ,PDT.[Name] ,SPT.[Name] ,SPT.[Description] ,STY.[Number] ,STY.Title ,TSK.[Name] ,SCY.Catagory ,NSS.IncidentNumber ,APP.AppName ,STY.KanBanProductId ,STY.SprintId ,NSS.[Description] ,TSK.OriginalEstimateHours ,STY.Effort ,DTH.PointPerson ,DTH.NonScrumStoryId HAVING SUM(DTH.[Hours]) > 0 -- UNION ALL -- -- Sub-TOTAL by PERSON -- SELECT '4' AS RowType ,DTH.EnteredBy AS Person ,'' AS Project ,'' AS ProjectType ,'' AS Theme ,'' AS StoryNumber ,'' AS StoryTitle ,'' AS Effort ,'Subtotal:' AS Task ,'' AS OriginalEstimateHours ,'' AS Category ,'' AS IncidentNumber ,'' AS ApplicationName ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 2 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS MondayHours ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 3 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS TuesdayHours ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 4 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS WednesdayHours ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 5 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS ThursdayHours ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 6 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS FridayHours ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 7 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS SaturdayHours ,CAST(SUM(CASE WHEN DATEPART(dw, DTH.ActivityDate) = 1 THEN DTH.[Hours] ELSE 0 END) AS VARCHAR(20)) AS SundayHours ,CAST(SUM(DTH.[Hours]) AS VARCHAR(20)) AS TotalHours ,'' AS DifferentUsers ,'' AS DoubleBookedFlag ,'' AS PointPerson FROM DailyTaskHours DTH LEFT JOIN Task TSK ON DTH.TaskId = TSK.PK_Task LEFT JOIN Story STY ON TSK.StoryId = STY.PK_Story LEFT JOIN Product PDT ON STY.ProductId = PDT.PK_Product LEFT JOIN [User] USR ON DTH.EnteredBy = USR.DisplayName WHERE DTH.EnteredBy LIKE @userParam AND ActivityDate >= @startDateParam AND ActivityDate <= @endDateParam AND 1 = CASE ISNUMERIC(@productId) WHEN 0 THEN CASE WHEN DTH.TaskId IS NULL OR PDT.PK_Product LIKE @productId THEN 1 END WHEN 1 THEN CASE WHEN DTH.TaskId IS NOT NULL AND PDT.PK_Product = @productId THEN 1 END END AND ( ( @orgTeamPK = '%' AND ( USR.[OrganizationalTeamId] LIKE @orgTeamPK OR USR.[OrganizationalTeamId] IS NULL ) ) OR ( @orgTeamPK <> '%' AND (USR.[OrganizationalTeamId] LIKE @orgTeamPK) ) ) AND ( ( STY.Number LIKE @search OR STY.Number IS NULL ) OR ( STY.Title LIKE @search OR STY.Title IS NULL ) OR ( TSK.NAME LIKE @search OR TSK.NAME IS NULL ) ) AND ( ( @theme = '%' AND ( dbo.primaryTheme(STY.[Number]) LIKE @theme OR dbo.primaryTheme(STY.[Number]) IS NULL ) ) OR ( @theme != '%' AND dbo.primaryTheme(STY.[Number]) = @theme ) ) GROUP BY DTH.EnteredBy HAVING SUM(DTH.[Hours]) > 0 ) AS My_View ORDER BY Person ,RowType ,Project ,ProjectType ,StoryNumber ,StoryTitle ,Task "> <SelectParameters> <asp:QueryStringParameter Name="userParam" Type="String" DefaultValue="%" /> <asp:QueryStringParameter Name="startDateParam" Type="String" /> <asp:QueryStringParameter Name="endDateParam" Type="String" /> <asp:QueryStringParameter Name="orgTeamPK" Type="String" DefaultValue="%" /> <asp:QueryStringParameter Name="productId" Type="String" DefaultValue="%" /> <asp:QueryStringParameter Name="search" Type="String" DefaultValue="%" /> <asp:QueryStringParameter Name="theme" Type="String" /> </SelectParameters> </asp:SqlDataSource> ```
Your database engine is not doing that, ASP.NET is doing it. It is a security feature to help prevent XSS. You can set the **HtmlEncode** property on the bound field like the example at this [MSDN](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.htmlencode%28v=vs.110%29.aspx) link: ``` <asp:boundfield datafield="City" htmlencode="false" headertext="City"/> ```
In your application, you probably want to do an `HttpUtility.HtmlDecode` on the string. From MSDN: > Converts a string that has been HTML-encoded for HTTP transmission into a decoded string. <http://msdn.microsoft.com/en-us/library/system.web.httputility.htmldecode(v=vs.110).aspx> In fact, it's probably preferred to append the `<br />` in the application itself, not in the query. It's not typical to massage data in this way at the query itself. Typically the data being fetched for your application should not have any presentation-layer or view type stuff attached to it, unless that's exactly how it exists in the database. Save that work for your application. For example, if this is an MVC application, you may consider doing that kind of work in the controller. **More...** Now that I see the full context of your question from the code you've just posted, I'll add the same comment I make below to this answer for any future readers. It's been a while since I've been in ASP.NET WebForms land, so I may be a little rusty! My comment... > There are better ways to handle this but I'm afraid it may be out of the scope of this question since it would also involve how you've created your data sources. If you're interested, a quick search resulted [in this example](http://www.codeproject.com/Articles/27260/Repeater-within-Gridview-in-C-ASP-NET-2-0) of a `Repeater` inside a `GridView` and a data source with two related data tables. It's an old example (.NET 2.0), but it may be still valid or at least should help lead you to a better example. **And now for an alternative answer? ...** I can think of another option specific to your question. In the query, instead of appending a `<br />`, you can append a straightforward new line (`\n` or char(10) in SQL). Then, instead of using an `asp:BoundColumn` for that field in your `GridView`, use an `asp:TemplateField` and inside the template, replace the `\n` with a `<br />`. Like I said earlier, it's been a while since I've done WebForms, but I believe it would look something like: ``` <%#Eval("Task").Replace("\n", "<br />")%> ``` I suppose you could do similar using `HtmlDecode`, but I don't like seeing the HTML tags in those query results.
Rendering line breaks in HTML from SQL datasource
[ "", "asp.net", "sql", "sql-server", "datasource", "" ]
So if you look at the last `WHERE` clause. `Where inv_location_id in` One of them I am using an `integer` and the other is a `set`. How can I combine these? ``` IF ( @inventory_location_id = NULL ) SELECT clinic_desc , dbo.fn_get_clinic_address_formatted(@application_name, clinic_id, NULL, NULL, 'STANDARD', NULL, NULL, NULL, NULL) AS formatted_address , vfc_pin , contact , email_address , phone , fax FROM dbo.clinics WHERE clinic_id IN ( SELECT clinic_id FROM dbo.clinic_inv_locations WHERE inv_location_id IN ( SELECT ilr.clinic_id FROM dbo.inv_location_reconciliation ilr WHERE inv_location_reconciliation_id = @reconciliation_id ) ) ELSE SELECT clinic_desc , dbo.fn_get_clinic_address_formatted(@application_name, clinic_id, NULL, NULL, 'STANDARD', NULL, NULL, NULL, NULL) AS formatted_address , vfc_pin , contact , email_address , phone , fax FROM dbo.clinics WHERE clinic_id IN ( SELECT clinic_id FROM dbo.clinic_inv_locations WHERE inv_location_id IN ( @inventory_location_id ) ) ```
Just change the where to be ``` WHERE ( ( @inventory_location_id IS NULL AND ( inv_location_id IN ( SELECT ilr.clinic_id FROM dbo.inv_location_reconciliation ilr WHERE inv_location_reconciliation_id = @reconciliation_id ) ) ) OR ( @inventory_location_id IS NOT NULL AND ( inv_location_id IN ( @inventory_location_id ) ) ) ) ``` It can be made more concise, but I left it big and wordy for clarity here :)
I like CTEs with complicated queries because I think it makes them easier to read, so I would do something like below. There are many other ways to solve this problem and I don't claim this is the the fastest. *I haven't tested it so proceed with caution* ``` with clinic_list AS ( SELECT ilr.clinic_id as clinic_id FROM dbo.inv_location_reconciliation ilr WHERE inv_location_reconciliation_id = @reconciliation_id UNION ALL SELECT clinic_id FROM dbo.clinic_inv_locations WHERE inv_location_id IN ( @inventory_location_id ) ) SELECT clinic_desc , dbo.fn_get_clinic_address_formatted(@application_name, clinic_id, NULL, NULL, 'STANDARD', NULL, NULL, NULL, NULL) AS formatted_address , vfc_pin , contact , email_address , phone , fax FROM dbo.clinics WHERE clinic_id IN (SELECT clinic_id FROM clinic_list) ``` I also have a strong **suspicion** that using a function here is the wrong choice. Functions are quite horrible in SQL and are often the cause of bad performance and scaling.
How can I combine this sql where clause to use one Select?
[ "", "sql", "t-sql", "" ]
I am working with Microsoft SQL Server 2012. I have two tables T1 and T2 and they both have an `ID` column. When I enter the following SQL statement in my Microsoft SQL Server Management Studio ``` select ID from T1 natural full outer join T2 ``` it generated the following error: > Msg 102, Level 15, State 1, Line 1 > Incorrect syntax near 'T2'. However, Microsoft SQL Server Management Studio accepts the following statement which I think is an equivalent statement: ``` select ID from T1 full outer join T2 ON t1.ID = T2.ID ``` Does SQL Server Management Studio not support natural full outer join?
There are no Natural JOINS in Sql server, You have to explicitly tell sql server on which fields you want table to join. 1) Using `ON` clause and explicitly using the column names from both tables. 2) Or in older JOIN Syntax explicitly using the column names from both tables in WHERE Clause. for another nice answer on this topic `Read here`
SQL Server/Transact SQL simply doesn't support Natural Join syntax. Btw, the parser is not complaining about the "natural" because it assumes this is a table alias :-)
Natural full outer join does not work in my SQL Server Management Studio
[ "", "sql", "sql-server", "sql-server-2012", "" ]
So I have received this error: #1066 - Not unique table/alias: 'Purchase' I am trying to do the following: ``` SELECT Blank.BlankTypeCode ,Blank.BlankCode ,Payment.Amount ,Payment.Type ,Purchase.PurchaseDate ,Payment.DatePaid FROM Blank INNER JOIN Ticket ON Blank.BlankCode = Ticket.Blank_BlankCode INNER JOIN MCO_Blank ON Blank.BlankCode = MCO_Blank.Blank_BlankCode INNER JOIN Purchase ON Ticket.PurchaseID = Purchase.PurchaseID INNER JOIN Purchase ON MCO_Blank.PurchaseID = Purchase.PurchaseID INNER JOIN Payment ON Ticket.PurchaseID = Payment.PurchaseID INNER JOIN Payment ON MCO_Blank.PurchaseID = Payment.PurchaseID WHERE Payment.Status = "Paid"; ``` Blank Table consists of: ``` BlankCode, IssueDate, Status, UserID, BlankTypeCode ``` Payment Table consists of: ``` Type, Amount, Status, DueDate, PurchaseID, CurrencyRateDate ``` Purchase Table consists of: ``` PurchaseID, CustomerID, PurchaseDate, TotalFare, TaxAmount, CurrencyType, Purchasecol ``` Ticket Table consists of: ``` Price, PurchaseID, Blank_BlankCode, Blank_BlankTypeCode, TicketType, Airline_Name ``` MCO\_Blank Table consists of: ``` Service, Cost, Description, Purchase_PurchaseID, Blank_BlankCode, Blank_BlankTypeCode ``` I am unsure of how I can make this work.
You need to use table aliases. You have mentioned the same table more than once in the `from` clause. The query is something like this: ``` SELECT b.BlankTypeCode, b.BlankCode, pa1.Amount, pa1.Type, p1.PurchaseDate, pa2.DatePaid FROM Blank b INNER JOIN Ticket t ON b.BlankCode = t.Blank_BlankCode INNER JOIN MCO_Blank mb ON b.BlankCode = mb.Blank_BlankCode INNER JOIN Purchase p1 ON t.PurchaseID = p1.PurchaseID INNER JOIN Purchase p2 ON mb.PurchaseID = p2.PurchaseID INNER JOIN Payment pa1 ON t.PurchaseID = pa1.PurchaseID INNER JOIN Payment pa2 ON mc.PurchaseID = pa2.PurchaseID WHERE pa1.Status = "Paid"; ``` I had to make a guess at which payment and purchase is intended for the aliases. These may not be correct in the `from` and `where` clauses.
You need a different alias for the table each time you use it. ``` SELECT B.BlankTypeCode, B.BlankCode, A1.Amount, A1.Type, P1.PurchaseDate, P1.DatePaid FROM Blank AS B JOIN Ticket AS T ON B.BlankCode = T.Blank_BlankCode JOIN MCO_Blank AS M ON B.BlankCode = M.Blank_BlankCode JOIN Purchase AS P1 ON T.PurchaseID = P1.PurchaseID JOIN Purchase AS P2 ON M.PurchaseID = P2.PurchaseID JOIN Payment AS A1 ON T.PurchaseID = A1.PurchaseID JOIN Payment AS A2 ON M.PurchaseID = A2.PurchaseID WHERE A1.Status = "Paid" AND A2.Status = "Paid" ``` You'll need to sort out which versions of the Purchase and Payment tables the selected columns come from, and also what should be in the WHERE clause really.
Inner Joining the same table multiple times
[ "", "sql", "inner-join", "" ]
I'm stuck a little with a combine MySQL query. It's a part of a multi-language, multi-destination site, so I need to retrieve some text parts of the site from multiple table, with fallback. Order of possible hits: > corrected@local\_tbl > english@local\_tbl > corrected@global\_tbl > > english@global\_tbl. Because it'll be highly used, I'd like to keep it fast and with low number of connections, but returning only 1 row. I tried a few approaches as follows, but I'm sure there is a better solution. --- Subquery in FROM clause: It dies if any of subquery gives 0 rows. Even if it works, needs some php interpret: ``` SELECT * FROM (SELECT `sp_content` AS sp_local FROM `loc-ae_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'de' AND `sp_corrected`='1' LIMIT 1) as local, (SELECT `sp_content` AS sp_local_en FROM `loc-ae_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'en' LIMIT 1) as local_en, (SELECT `sp_content` AS sp_global, `sp_corrected` as sp_global_corrected FROM `loc-global_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'de' LIMIT 1) as global, (SELECT `sp_content` AS sp_global_en FROM `loc-global_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'en' LIMIT 1) as global_en ``` --- TEMP Table: Here I am concerned about performance, can't use memory engine because it involves a text field. Wasted nuke for a birdie? ``` CREATE TEMPORARY TABLE IF NOT EXISTS `random_tbl_name` AS (SELECT `sp_content` FROM `loc-global_siteparts` LIMIT 0); INSERT INTO `random_tbl_name` SELECT `sp_content` FROM `loc-ae_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'de' AND `sp_corrected` = '1' LIMIT 1; INSERT INTO `random_tbl_name` SELECT `sp_content` FROM `loc-ae_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'en' LIMIT 1; INSERT INTO `random_tbl_name` SELECT `sp_content` FROM `loc-global_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'de' AND `sp_corrected` = '1' LIMIT 1; INSERT INTO `random_tbl_name` SELECT `sp_content` FROM `loc-global_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'en' LIMIT 1; SELECT * FROM `random_tbl_name` LIMIT 1; ``` **EDIT:** Thanks for all answers, they were really helpful.
``` SELECT * FROM ((SELECT 1 precedence, `sp_content` FROM `loc-ae_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'de' AND `sp_corrected`='1' LIMIT 1) UNION (SELECT 2 precedence, `sp_content` FROM `loc-ae_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'en' LIMIT 1) UNION ... ) x ORDER BY precedence LIMIT 1 ```
The reason you get no result when one of the subqueries is empty is, with ``` select * from s1, s2, s3, s4 ``` you have an implicit join. And when one of the sub-results is empty, the resulting join is empty as well. To solve this, you can use your subqueries as columns. This will give you the same result, but with NULL values, where the subselect returns no rows ``` SELECT (SELECT `sp_content` AS sp_local FROM `loc-ae_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'de' AND `sp_corrected`='1' LIMIT 1) as local, (SELECT `sp_content` AS sp_local_en FROM `loc-ae_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'en' LIMIT 1) as local_en, (SELECT `sp_content` AS sp_global, `sp_corrected` as sp_global_corrected FROM `loc-global_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'de' LIMIT 1) as global, (SELECT `sp_content` AS sp_global_en FROM `loc-global_siteparts` WHERE `sp_name` = 'name_of_some_sitepart' AND `sp_lang` = 'en' LIMIT 1) as global_en ```
MySQL multi-table SELECT
[ "", "mysql", "sql", "select", "subquery", "multiple-tables", "" ]
I need to use my horizontal query result to another SQL query. How to do it, Please help. Suppose I have two Tables: ``` Tab1: ________________________________________ |ID | ARID | SEQ1 | SEQ2 | SEQ3 | SEQ4 | |___|______|______|______|______|______| |a1 | ar01 | A | C | B | D | |a2 | ar02 | C | D | A | B | |___|______|______|______|______|______| Tab2: _____________________ |ARID | SEQN | CODE | |_____|______|______| |ar01 | A | 1 | |ar01 | G | 4 | |ar01 | B | 2 | |ar01 | D | 3 | |ar01 | C | 8 | |ar01 | F | 6 | |ar01 | E | 5 | |ar01 | H | 7 | |ar02 | A | 1 | |ar02 | H | 8 | |_____|______|______| ``` Well I need result something like this: ``` ResultTab: _____________________ |ARID | SEQN | CODE | |_____|______|______| |ar01 | A | 1 | |ar01 | C | 8 | |ar01 | B | 2 | |ar01 | D | 3 | |_____|______|______| ``` It will fetch `SEQ1`, `SEQ2`, `SEQ3` and `SEQ4` for a certain `ARID` from `Tab1` and return the mapped values from `Tab2` for that `ARID`. Please help me. Thank you...
Please use `UNION ALL` to get benefit of INDEX. ``` SELECT t1.ARID, t1.SEQ1 AS SEQN FROM Tab1 t1 INNER JOIN Tab2 t2 ON t1.ARID = t2.ARID WHERE t1.ARID = 'ar01' AND t1.SEQN = t2.SEQ1 UNION ALL SELECT t1.ARID, t1.SEQ2 AS SEQN FROM Tab1 t1 INNER JOIN Tab2 t2 ON t1.ARID = t2.ARID WHERE t1.ARID = 'ar01' AND t1.SEQN = t2.SEQ2 UNION ALL SELECT t1.ARID, t1.SEQ3 AS SEQN FROM Tab1 t1 INNER JOIN Tab2 t2 ON t1.ARID = t2.ARID WHERE t1.ARID='ar01' AND t1.SEQN = t2.SEQ3 UNION ALL SELECT t1.ARID, t1.SEQ4 AS SEQN FROM Tab1 t1 INNER JOIN Tab2 t2 ON t1.ARID = t2.ARID WHERE t1.ARID='ar01' AND OR t1.SEQN = t2.SEQ4 ```
try this for `ARID='ar01'` ``` SELECT A.* FROM Tab2 A, Tab1 B WHERE A.ARID='ar01' AND A.ARID=B.ARID AND (A.SEQN=B.SEQ1 OR A.SEQN=B.SEQ2 OR A.SEQN=B.SEQ3 OR A.SEQN=B.SEQ4) ```
How to use my horizontal query result to another SQL query
[ "", "mysql", "sql", "sql-server", "" ]
Let`s say I have the following table ``` +----+-------+ | Id | Value | +----+-------+ | 1 | 2.0 | | 2 | 8.0 | | 3 | 3.0 | | 4 | 9.0 | | 5 | 1.0 | | 6 | 4.0 | | 7 | 2.5 | | 8 | 6.5 | +----+-------+ ``` I want to plot these values, but since my real table has thousands of values, I thought about getting and average for each X rows. Is there any way for me to do so for, ie, each 2 or 4 rows, like below: ``` 2 +-----+------+ | 1-2 | 5.0 | | 3-4 | 6.0 | | 5-6 | 2.5 | | 7-8 | 4.5 | +-----+------+ 4 +-----+------+ | 1-4 | 5.5 | | 5-8 | 3.5 | +-----+------+ ``` Also, is there any way to make this X value dynamic, based on the total number of rows in my table? Something like, if I have 1000 rows, the average will be calculated based on each 200 rows (1000/5), but if I have 20, calculate it based on each 4 rows (20/5). I know how to do that programmatically, but is there any way to do so using pure SQL? EDIT: I need it to work on mysql.
Depending on your DBMS, something like this will work: ``` SELECT ChunkStart = Min(Id), ChunkEnd = Max(Id), Value = Avg(Value) FROM ( SELECT Chunk = NTILE(5) OVER (ORDER BY Id), * FROM YourTable ) AS T GROUP BY Chunk ORDER BY ChunkStart; ``` This creates 5 groups or chunks no matter how many rows there are, as you requested. If you have no windowing functions you can fake it: ``` SELECT ChunkStart = Min(Id), ChunkEnd = Max(Id), Value = Avg(Value) FROM YourTable GROUP BY (Id - 1) / (((SELECT Count(*) FROM YourTable) + 4) / 5) ; ``` I made some assumptions here such as `Id` beginning with 1 and there being no gaps, and that you would want the last group too small instead of too big if things didn't divide evenly. I also assumed integer division would result as in Ms SQL Server.
You can use modulos operator to act on every Nth row of the table. This example would get the average value for every 10th row: ``` select avg(Value) from some_table where id % 10 = 0; ``` You could then do a count of the rows in the table, apply some factor to that, and use that value as a dynamic interval: ``` select avg(Value) from some_table where id % (select round(count(*)/1000) from some_table) = 0; ``` You'll need to figure out the best interval based on the actual number of rows you have in the table of course. EDIT: Rereading you post I realize this is getting an average of every Nth row, and not each sequential N rows. I'm not sure if this would suffice, or if you specifically need sequential averages.
Get Average value for each X rows in SQL
[ "", "mysql", "sql", "" ]
How do I get the current records based on it's Effective Date? Should I use a subquery? Is there anything I could use aside from MAX? I have these table examples. ``` ResourceID is the ID number of the Resource. OrganizationId is the current Organization or Department of the Resource. Effective Date is the start date or the first day of the Resource in an Organization. ResourceID OrganizationID EffectiveDate VC1976 INTIN1HTHWYAMM 2009-12-23 00:00:00.000 VC1976 INTIN1LGAMMAMS 2011-07-01 00:00:00.000 VC1976 SMESM1HTOVEOVE 2012-07-01 00:00:00.000 VC1976 APCAP1HTOVEOVE 2012-07-09 10:17:56.000 ResourceID OrganizationID EffectiveDate JV2579 VNMVN1HTHWYCMM 2009-07-01 00:00:00.000 JV2579 INTIN1HTHWYCMM 2011-07-02 00:00:00.000 JV2579 SMESM1HTOVEOVE 2012-07-01 00:00:00.000 ResourceID OrganizationID EffectiveDate RJ1939 INTIN1HTOVEOVE 1995-01-30 00:00:00.000 RJ1939 INTIN1HTOVEOVE 2007-07-25 00:00:00.000 RJ1939 SMESM1HTOVEOVE 2012-07-01 00:00:00.000 ResourceID OrganizationID EffectiveDate PJ8828 AREAR1HTHWYRHD 2012-04-01 00:00:00.000 PJ8828 SMESM1HTOVEOVE 2012-07-01 00:00:00.000 ResourceID OrganizationID EffectiveDate RS1220 INTIN1HTHWYCMM 1981-01-06 00:00:00.000 RS1220 SMESM1HTOVEOVE 2012-07-01 00:00:00.000 ``` My goal is to get all of the ResourceID who **currently** belongs to the OrganizationUnit that the user puts in. For example, If the User puts **SMESM1HTOVEOVE** in the OrganizationID parameter then it pull out all ReourceID that is currently under **SMESM1HTOVEOVE**. So far my MAX query below does not work. ``` select OrganizationID, ResourceID, MAX(EffectiveDate) as EffectiveDate from ResourceOrganization where OrganizationID = 'SMESM1HTOVEOVE' group by OrganizationID, ResourceID, EffectiveDate ``` Below are the results of my short MAX query above. This is wrong because ResourceID **VC1976** currently belongs to APCAP1HTOVEOVE effective on 2012-07-09 10:17:56.000. ``` OrganizationID ResourceID EffectiveDate SMESM1HTOVEOVE JV2579 2012-07-01 00:00:00.000 SMESM1HTOVEOVE PJ8828 2012-07-01 00:00:00.000 SMESM1HTOVEOVE RJ1939 2012-07-01 00:00:00.000 SMESM1HTOVEOVE RS1220 2012-07-01 00:00:00.000 SMESM1HTOVEOVE VC1976 2012-07-01 00:00:00.000 ``` Can someone help provide their input please? Because I will use this for my stored proc below. I'll also include my proc for you own perusal. Thank you! ``` create table #Resources ( ResourceID nvarchar(30), OrganizationID nvarchar(15), EffectiveDate datetime, TimeEntryDate datetime ) if @ResourceID <> '' begin insert into #Resources (ResourceID,OrganizationID,EffectiveDate) select ro.ResourceID, ro.OrganizationID, ro.EffectiveDate from ResourceOrganization ro, (select ResourceID, MAX(EffectiveDate) as maxEffectivedate from dbo.ResourceOrganization where ResourceID = @ResourceID group by ResourceID) as maxresults where ro.ResourceID = maxresults.ResourceID and ro.EffectiveDate = maxresults.maxEffectivedate end else if @OrgUnit <> '' begin insert into #Resources (ResourceID,OrganizationID,EffectiveDate) select ro.ResourceID, ro.OrganizationID, ro.EffectiveDate from ResourceOrganization ro, (select ResourceID, MAX(EffectiveDate) as maxEffectivedate from dbo.ResourceOrganization where OrganizationID like '' + @OrgUnit + '%' group by ResourceID) as maxresults where ro.ResourceID = maxresults.ResourceID and ro.EffectiveDate = maxresults.maxEffectivedate else if @ResourceID <> '' and @OrgUnit <> '' begin insert into #Resources (ResourceID,OrganizationID,EffectiveDate) select ro.ResourceID, ro.OrganizationID, ro.EffectiveDate from ResourceOrganization ro, (select ResourceID, MAX(EffectiveDate) as maxEffectivedate from dbo.ResourceOrganization where ResourceID = @ResourceID group by ResourceID) as maxresults where ro.ResourceID = maxresults.ResourceID and ro.EffectiveDate = maxresults.maxEffectivedate end ```
I suppose there's other ways to do this, but I think this works: ``` DECLARE @OrganizationID varchar(40) SET @OrganizationID = 'SMESM1HTOVEOVE' SELECT ro.ResourceID, ro.OrganizationID, max(ro.EffectiveDate) FROM ResourceOrganization ro WHERE ro.OrganizationID = @OrganizationID GROUP BY ro.ResourceID, ro.OrganizationID HAVING max(ro.EffectiveDate) = ( SELECT max(EffectiveDate) FROM ResourceOrganization WHERE ResourceID = ro.ResourceID) ``` Here's a [SQLFiddle](http://sqlfiddle.com/#!3/097b7a/9) to play with. EDIT: Actually, that's probably over-complicated. Try this one: ``` DECLARE @OrganizationID varchar(40) SET @OrganizationID = 'SMESM1HTOVEOVE' SELECT ro.ResourceID, ro.OrganizationID, ro.EffectiveDate FROM ResourceOrganization ro WHERE ro.OrganizationID = @OrganizationID AND ro.EffectiveDate = ( SELECT max(EffectiveDate) FROM ResourceOrganization WHERE ResourceID = ro.ResourceID) ```
You may also try this using CTE ``` ;WITH tmpWithUID As ( SELECT Row_Number() OVER(ORDER BY ResourceID, EffectiveDate, OrganizationID) AS rowNumber, ResourceID, OrganizationID, EffectiveDate FROM dbo.ResourceOrganization GROUP BY ResourceID, EffectiveDate, OrganizationID ) SELECT ResourceID, OrganizationID, EffectiveDate FROM tmpWithUID WHERE tmpWithUID.rowNumber IN ( SELECT max(rowNumber) rowNumber FROM tmpWithUID GROUP BY ResourceID ) AND OrganizationID = 'SMESM1HTOVEOVE' ```
How do I get the current records based on it's Effective Date?
[ "", "sql", "sql-server-2008", "" ]
I have two tables leagues and seasons.. seasons has `league_id, start_date` I am trying to grab the latest season for each league.. and then order the results by the season's start date in asc order. ``` SELECT * FROM leagues JOIN ( SELECT id as season_id, title as season_title, league_id, start_date FROM seasons ORDER BY start_date DESC) AS seasons ON leagues.id = seasons.league_id ORDER BY seasons.start_date ASC; ``` I have been working on this for a while now.. this kind of works but grabs multiple season records for one league.. I found a solution using PHP but I am looking to do this only using MYSQL. Any advice is appreciated.
You will need to use a `MAX()` aggregate in the subquery to get the latest `start_date` per season, and join that back against the `seasons` table. ``` SELECT /* Don't SELECT * in production code - trim this to just the columns you actually need */ leagues.*, seasons.* FROM /* Start with an inner join between seasons and leagues */ leagues INNER JOIN seasons ON leagues.id = seasons.league_id INNER JOIN ( /* Subquery gets leage_id and latest start date per league_id group */ SELECT league_id, MAX(start_date) AS maxstart FROM seasons GROUP BY league_id /* joining back to seasons on both of those columns to return the full season column data */ ) maxseason ON seasons.league_id = maxseason.league_id AND seasons.start_date = maxseason.startdate ORDER BY seasons.start_date ASC ```
You can do this quite simply and without subqueries using a self-join: ``` SELECT s1.*, l.* FROM seasons s1 LEFT JOIN seasons s2 ON s2.league_id = s1.league_id AND s2.start_date > s1.start_date JOIN leagues l ON l.id = s1.league_id WHERE s2.league_id IS NULL ORDER BY s1.start_date ``` This method generally outperforms subqueries.
MYSQL subquery using order by and group by
[ "", "mysql", "sql", "" ]
I am trying to write a query to generate automated report. This report is to run for last month's transactions it should run on 1st of every month. I have job to run this report to run 1st of every month. But how can I make this query to choose no of days in a month? (some months will have 30 and some will have 31 and in feb no of days changes based on leap year). Here one more requirement is I only have to pass one parameter in the query. below is example of query that I have now ``` select id,name,address,trans_dt from tab1 where trans_dt between to_date('&1','MM-DD-YYYY')-30 AND to_date('&1','MM-DD-YYYY'); ``` The above query is generating last 30 days transactions, but it will be wrong if no days for month is 31 or 28. I am using oracle 11r2 as database. Please help in writing this.
Found solution but forget to reply here. Here is my solution ``` select id,name,address,trans_dt from tab1 where trans_dt between trunc(trunc(sysdate,'MM')-1,'MM') and trunc(sysdate,'MM'); ``` above will give you report from 1st day of month to last day of month from calender.
mySQL ``` SELECT id, NAME, address, trans_dt FROM tab1 WHERE MONTH(trans_dt) = 02 /* Param for month passed in */ AND YEAR(trans_dt) = YEAR(CURDATE()) ``` Oracle ``` SELECT id, NAME, address, trans_dt FROM tab1 WHERE to_char( dt_column, 'mm' ) = 02 /* Param for month passed in */ AND EXTRACT(YEAR FROM DATE trans_dt) = trunc(sysdate, 'YEAR') ``` Maybe this can work? I only really know mySQL
How to write a Report query based on number of days in a month?
[ "", "sql", "oracle11g", "" ]
What does this part of code do? ``` ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; ``` I've searched on the internet about the MyISAM and it's the default storage engine, and the CHARSET=utf8 is used for special characters.
`ENGINE=MyISAM` Set DB Engine sample it And InnoDB ... `AUTO_INCREMENT=1` Set Start number of `id` Or Primary KEY `DEFAULT CHARSET=utf8;` SET charset For Other Languages Or other char's This code is part of DB config And usually used in .sql files ... This code is Query And Used in MySQL Database's
You almost got it. with `ENGINE=MyISAM` you specify that you are using `MyISAM` engine. with `AUTO_INCREMENT=1` you are resetting the `auto-increment`field to start from 1. with `DEFAULT CHARSET=utf8` to specify default server character set and collation.
What does this code in SQL do?
[ "", "mysql", "sql", "" ]
I am trying to delete the contents of some tables. I want the user to select the table names and these are concatenated to a string. eg: `Brands,Products,ProductGroups` this string is passed to the stored procedure `DBReset`. I have a function to split the string and return the values as a table. It works fine. Now I want to delete the contents of the 3 tables (excluding contents with branchID =0) returned from the function called `Split`. Here is what I have tried: ``` CREATE PROCEDURE DBReset (@Tables varchar(200)) AS BEGIN DELETE FROM (SELECT Items FROM [dbo].[Split] (@Tables, ',')) WHERE BranchID<>0 END ``` Which gives error: ``` Incorrect syntax near '('. Incorrect syntax near the keyword 'WHERE'. ``` Then I tried dynamic sql: ``` EXEC('DELETE FROM (SELECT Items FROM [dbo].[Split] ('+@Tables+', '','')) WHERE BranchID<>0') ``` It gives the same error when executing. Is there any possible way to do this? Thanks for sharing your valuable time.
## APPROACH 1: You cannot delete from multiple tables from a single query (Unless you have a foreign key constraint between your tables and activate the "cascade delete" option on the constraint) In your case, the most simple approach would be to replace the comma as shown below and use dynamic SQL: ``` DECLARE @CONDITION VARCHAR(255) SET @CONDITION = ' WHERE BRANCHID <> 0; DELETE FROM ' SET @TABLELIST = 'DELETE FROM ' + REPLACE(@Tables,',',@CONDITION)+' WHERE BRANCHID <> 0;' EXEC (@TABLELIST) ``` ## APPROACH 2: If you are going to use the split function approach, you need to return the Table Names in the split function & can use dynamic SQL: 1. Create function to return Table Names: ``` CREATE FUNCTION dbo.SPLIT_FUNTION( @SINPUTLIST VARCHAR(MAX) -- Your data to be split , @SDELIMITER VARCHAR(5000) = ',' -- The Delimited that is used for splitting ) RETURNS @TABLELIST TABLE (TABLE_NAMES VARCHAR(5000)) BEGIN DECLARE @ITEMLIST VARCHAR(MAX) WHILE CHARINDEX(@SDELIMITER,@SINPUTLIST,0) <> 0 BEGIN SELECT @ITEMLIST=RTRIM(LTRIM(SUBSTRING(@SINPUTLIST,1,CHARINDEX(@SDELIMITER,@SINPUTLIST,0)-1))), @SINPUTLIST=RTRIM(LTRIM(SUBSTRING(@SINPUTLIST,CHARINDEX(@SDELIMITER,@SINPUTLIST,0)+LEN(@SDELIMITER),LEN(@SINPUTLIST)))) IF LEN(@ITEMLIST) > 0 INSERT INTO @TABLELIST SELECT @ITEMLIST END IF LEN(@SINPUTLIST) > 0 INSERT INTO @TABLELIST SELECT @SINPUTLIST RETURN END ``` 2. Form & execute delete statement: ``` DECLARE @DELETE_STATEMENT VARCHAR(MAX) SELECT @DELETE_STATEMENT = COALESCE(@DELETE_STATEMENT + ' WHERE BRANCHID <> 0 ; ', '') + 'DELETE FROM '+ TABLE_NAMES FROM DBO.SPLIT_FUNTION(@TABLES,',') EXEC (@DELETE_STATEMENT) -- DELETE ```
you will most likely need to iterate over the result set from the split, and then use exec to execute the sql with the table in the scope of the current iteration of the loop, adding in your where clause as you go. you can do this via a cursor, or within a while loop.
Delete contents from tables specified by user
[ "", "sql", "sql-server-2008", "stored-procedures", "" ]
``` #Region "FillListView" Sub FillListview() LV.Items.Clear() myqry = "SELECT AccResult.StudNo,Exercises.ID from AccResult INNER JOIN Exercises ON AccResult.StudNo = Exercises.ID ORDER BY AccResult.FirstName,AccResult.YrandSec Asc;" mycmd = New OleDbCommand(myqry, con) con.Open() mydr = mycmd.ExecuteReader While mydr.Read With LV .Items.Add(mydr("StudNo")) With .Items(.Items.Count - 1).SubItems .Add(mydr("CNumber")) .Add(mydr("FirstName")) .Add(mydr("LastName")) .Add(mydr("YrandSec")) .Add(mydr("Exer1")) .Add(mydr("Exer2")) .Add(mydr("Exer3")) .Add(mydr("Exer4")) .Add(mydr("Exer5")) End With End With End While con.Close() End Sub #End Region ``` `AccResult` is the name of my first table and `Exercises` is the second. My PK for `AccResult` is `StudNo` and for `Exercises` is `ID`. How can I join these two tables to display in `ListView`? `AccResult` Table: ``` StudNo (PK) CNumber FirstName LastName YrandSec ``` `Exercises` Table: ``` ID (PK) StudNo Exer1 Exer2 Exer3 Exer4 Exer5 ```
Your JOIN condition is incorrect. ``` AccResult INNER JOIN Exercises ON AccResult.StudNo = Exercises.ID ``` is joining the primary key of the parent table (AccResult.StudNo) with the primary key of the child table (Exercises.ID). You need to join the primary key of the parent table (AccResult.StudNo) with the **foreign key** of the child table (Exercises.StudNo), i.e., ``` AccResult INNER JOIN Exercises ON AccResult.StudNo = Exercises.StudNo ```
Not sure if I get the question correctly, but it looks like the query only select to columns : ``` myqry = "SELECT AccResult.StudNo,Exercises.ID from AccResult..." ``` then the code try to display all columns. Try to select all columns instead : ``` myqry = "SELECT * from AccResult..." ```
Inner Join in VB.Net
[ "", "mysql", "sql", "ms-access-2007", "inner-join", "vb.net-2010", "" ]
So I have this issue, I have this table Locations{id,name}. In a query how can I get the number of different permutations two by two? For example I have three locations: * Portugal * Spain * UK The combinations are * Portugal,Spain * Spain Portugal * Portugal,UK * UK,Portugal * Spain,UK * UK,Spain So the returned value should be 6. I can't get my head around this problem.
Do like this : ``` SELECT COUNT(1) FROM (SELECT t1.name as name1, t2.name as name2 FROM Locations t1, Locations t2 WHERE t1.name <> t2.name) ``` Here is an example <http://sqlfiddle.com/#!4/41a10/3>
As others have stated, if you just want the number, that's easy to do as it's just a math problem. If you actually want all the combinations, you're looking for a cartesian product, except you want identical pairs filtered out. See below - ``` with tbl as( select '01' as id, 'Portugal' as name from dual union all select '02' as id, 'Spain' as name from dual union all select '03' as id, 'UK' as name from dual ) select x.name, y.name from tbl x, tbl y where x.name <> y.name ``` Result: ``` NAME NAME Portugal Spain Portugal UK Spain Portugal Spain UK UK Portugal UK Spain ```
Oracle arrangements
[ "", "sql", "oracle", "" ]
Friends I am stuck in a stored procedure. I am unable to display distinct records. I have a name `USERS` and `Photos`. Both are inner join using `userID`. Since the table `Photos` has multiple records the search result is repeated. Friends can you help me fix this please? **Stored procedure:** ``` ALTER PROCEDURE dbo.homesearch @gender varchar(6), @age int, @age2 int, @religion varchar(50), @status varchar(11), @Country varchar(50), @City varchar(50) AS SELECT users.userID, photos.filename, users.userName, users.FirstName, users.LastName, users.nationality, users.Country, users.City, users.age, users.status FROM users INNER JOIN photos ON users.userID = photos.userID WHERE (users.age >= @age) AND (users.age <= @age2) AND (users.gender = @gender) AND (users.religion = @religion) AND (users.status = @status) AND (users.Country = @Country) AND (users.City = @City) RETURN ```
You can do something like this using `CROSS APPLY` ``` SELECT u.userID ,u.userName ,P.filename ,u.FirstName ,u.LastName ,u.nationality ,u.Country ,u.City ,u.age ,u.status FROM users u CROSS APPLY ( SELECT TOP 1 photos.filename FROM photos WHERE u.userID = userID ORDER BY photos.SomeColumn --<-- Pick a column here )p WHERE (u.age >= @age) AND (u.age <= @age2) AND (u.gender = @gender) AND (u.religion = @religion) AND (u.status = @status) AND (u.Country = @Country) AND (u.City = @City) ``` Pick a column by which you want to decide which TOP 1 filename you want to pick from Photos table for each user in users table. **Or using CTE** ``` ;With P_CTE AS ( SELECT TOP UserID, photos.filename, rn = ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY UserID) FROM photos ) SELECT users.userID, P_CTE.filename, users.userName, users.FirstName, users.LastName, users.nationality, users.Country, users.City, users.age, users.status FROM users INNER JOIN P_CTE ON users.userID = P_CTE.userID WHERE (users.age >= @age) AND (users.age <= @age2) AND (users.gender = @gender) AND (users.religion = @religion) AND (users.status = @status) AND (users.Country = @Country) AND (users.City = @City) AND P_CTE.rn = 1 ```
modify Your select query by :- ``` SELECT users.userID, photos.filename, users.userName, users.FirstName, users.LastName, users.nationality, users.Country, users.City, users.age, users.status FROM users INNER JOIN photos ON users.userID = photos.userID WHERE (users.age >= @age) AND (users.age <= @age2) AND (users.gender = @gender) AND (users.religion = @religion) AND (users.status = @status) AND (users.Country = @Country) AND (users.City = @City) GROUP BY users.userID, photos.filename, users.userName, users.FirstName, users.LastName, users.nationality, users.Country, users.City, users.age, users.status ``` and it will return unique results.
SQL Server : select distinct records with inner join and where clause
[ "", "asp.net", "sql", "sql-server", "" ]
My question is simple. I have two tables, a `product` table and an `image` table with multiple images of each product. `Product` table ``` +-----------+-------------+ | productId | ProductName | +-----------+-------------+ | 1 | product1 | | 2 | product2 | +-----------+-------------+ ``` `Image` table: ``` +---------+-----------+-----------+--+ | imageId | imagePath | productId | | +---------+-----------+-----------+--+ | 1 | img1 | 1 | | | 2 | img2 | 1 | | | 3 | img3 | 2 | | | 4 | img4 | 2 | | +---------+-----------+-----------+--+ ``` I want to get an output as below ``` +-----------+-------------+---------+-----------+--+ | productId | productName | imageId | imagePath | | +-----------+-------------+---------+-----------+--+ | 1 | product1 | 1 | img1 | | | 2 | product2 | 3 | img3 | | +-----------+-------------+---------+-----------+--+ ``` i.e. there should be only a single image corresponding to each product. Currently I have done this with cursor, but as an optimization I have to find another way. I am using SQL Server 2008. Thanks in advance...
You can select only one imageId (the minimum) per each productId by joining to filtered imageId like this : ``` SELECT p.ProductId, ProductName, i.imageId, imagePath FROM product p INNER JOIN Image i ON i.ProductId = p.ProductId INNER JOIN (SELECT MIN(imageId) As imageId, ProductId FROM image GROUP BY ProductId ) o ON o.imageId = i.imageId ``` or by filtering imageId using `WHERE` clause : ``` SELECT p.ProductId, ProductName, imageId, imagePath FROM product p INNER JOIN Image i ON i.ProductId = p.ProductId WHERE imageId IN (SELECT MIN(imageId) As imageId FROM image GROUP BY ProductId ) ``` ## [SQLFiddle Demo](http://sqlfiddle.com/#!3/53149/6)
In SQL Server 2005 I did this with a nested query that found min or max imageId grouped by productId. Maybe there's a better way in 2008. ``` select productId, productName, minImageId, imagePath from product inner join ( select productId, min(imageId) as minImageId from Image group by productId) minImages on product.id = minImages.productId ```
Join and get only single row with respect to each id
[ "", "sql", "sql-server", "sql-server-2008", "" ]
``` ID | user_id | name | active 1 | 1 | Profile 1 | f 2 | 1 | Profile 2 | t 3 | 2 | Profile 3 | f 4 | 2 | Profile 4 | f 5 | 3 | Profile 5 | f ``` I'm using PostgreSQL. In my application,`users` can create multiple `profiles` and I want to select last distinct **inactive profiles** created by each user. Also, if there is an `active` profile belongs to that user, it should not select any profile from that user -- that was the hard part for me. What kind of SQL statement I should use in order to get the following results? ``` 4 | 2 | Profile 4 | f 5 | 3 | Profile 5 | f ```
I would combine [`DISTINCT ON`](https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group/7630564#7630564) with [`NOT EXISTS`](http://www.postgresql.org/docs/current/interactive/functions-subquery.html#FUNCTIONS-SUBQUERY-EXISTS). Assuming a proper `boolean` type for active: ``` SELECT DISTINCT ON (user_id) id, user_id, name, active FROM profiles p WHERE NOT EXISTS ( SELECT 1 FROM profiles WHERE user_id = p.user_id AND active -- exclude users with any active profiles ) ORDER BY user_id, id DESC; ``` Probably fastest and cleanest.
[SQL Fiddle](http://sqlfiddle.com/#!15/de3c4/1) ``` select distinct on (user_id) id, user_id, name, active from t inner join ( select user_id from t group by user_id having not bool_or(active) ) s using(user_id) order by user_id, id desc ```
SQL statement to get distinct data
[ "", "sql", "postgresql", "greatest-n-per-group", "" ]
I've googled this for quite some time but I'm just not sure 'how' to pose the question so that google knows what I mean. I have an application that I'm developing in visual studio. Right now it's just a basic windows form with a search text box for a user to enter data and a search button to search the sql database and return the row that matches. The end user is searching for a student based on the entered student number. I have populated the sql db with two dummy students as to have data to test with. When I enter the first student number and click search, it works fine. When I enter the second number, works fine again. When I click search with no data in the box, works fine as well and throws me my custom error message. It's when I enter an invalid number, one that is not in the database, that nothing happens. It still shows the previous record I just successfully retrieved and clears the text box and puts the cursor back in the box and gives it focus (as it should) but doesn't tell me it can't find that specific number in the db. I can't seem to figure out how or where in my code to fix this. Background: I am self taught in programming languages (youtube segments, harvard's free online 'how to's', google, numerous books read, etc) and grasp the basic fundamentals of the syntax etc but no where near where I want to be. I LOVE developing software as a hobby and love learning how to do it. Any help is extremely appreciated. Just be gentle. :-) I have removed sensitive information on purpose and replaced them with '?'. Here is my current code: ``` Private Sub SearchButton_Click(sender As System.Object, e As System.EventArgs) Handles SearchButton.Click If stunumtxtbox.Text = "" Then MsgBox("Please enter a student number.", MsgBoxStyle.Exclamation) stunumtxtbox.Select() Else Try con.ConnectionString = "Data Source=?\?;Initial Catalog=?;Persist Security Info=True;User ID=?;Password=?" con.Open() Catch se As SqlException MsgBox(se.Message) Finally Try Dim dt As New DataTable Dim ds As New DataSet Dim da As New SqlDataAdapter ds.Tables.Add(dt) da = New SqlDataAdapter("SELECT DISTINCT * FROM Student_Info WHERE studentId = '" & stunumtxtbox.Text & "'", con) da.Fill(dt) For Each DataRow In dt.Rows If stunumtxtbox.Text = dt.Rows(0)("studentId").ToString Then fnametxtbox.Text = dt.Rows(0)("firstName").ToString mnametxtbox.Text = dt.Rows(0)("midleInitial").ToString lnametxtbox.Text = dt.Rows(0)("lastName").ToString addresstxtbox.Text = dt.Rows(0)("addressStreet").ToString address2txtbox.Text = dt.Rows(0)("addressOption").ToString citytxtbox.Text = dt.Rows(0)("addressCity").ToString statetxtbox.Text = dt.Rows(0)("addressState").ToString ziptxtbox.Text = dt.Rows(0)("addressZip").ToString countrytxtbox.Text = dt.Rows(0)("addressCountry").ToString celltxtbox.Text = dt.Rows(0)("contactcellphone").ToString studentidtxtbox.Text = dt.Rows(0)("studentId").ToString Else End If Next con.Close() Catch se As SqlException MsgBox(se.Message) Finally stunumtxtbox.Clear() stunumtxtbox.Select() Try StudentNameTextBox.Text = lnametxtbox.Text + "," + " " + fnametxtbox.Text + " " + mnametxtbox.Text Catch ex As Exception MsgBox(ex.Message) Finally fnamelabel.Visible = True mnamelabel.Visible = True lnamelabel.Visible = True addressstreetlabel.Visible = True address2label.Visible = True addresscitylabel.Visible = True addressstatelabel.Visible = True addressziplabel.Visible = True addresscountrylabel.Visible = True celllabel.Visible = True studentidlabel.Visible = True editbutton.Enabled = True editbutton.Visible = True End Try End Try End Try End If End Sub ```
Thank you @DonA and @Michael for helping me!! Using your info and a few more google's, I devised the following code and very happy to say that it works. :-) ``` Private Sub SearchButton_Click(sender As System.Object, e As System.EventArgs) Handles SearchButton.Click If stunumtxtbox.Text = "" Then MsgBox("Please enter a student number.", MsgBoxStyle.Exclamation) stunumtxtbox.Select() Else Try Using connection As New SqlConnection("Data Source=?;Initial Catalog=?;Persist Security Info=True;User ID=?;Password=?") connection.Open() Dim dt As New DataTable Dim ds As New DataSet Dim da As New SqlDataAdapter ds.Tables.Add(dt) da = New SqlDataAdapter("SELECT DISTINCT * FROM Student_Info WHERE studentId = '" & stunumtxtbox.Text & "'", connection) Dim count = da.Fill(dt) If count = 0 Then MsgBox("Student ID not found.", MsgBoxStyle.Critical) Else fnamelabel.Visible = True mnamelabel.Visible = True lnamelabel.Visible = True addressstreetlabel.Visible = True address2label.Visible = True addresscitylabel.Visible = True addressstatelabel.Visible = True addressziplabel.Visible = True addresscountrylabel.Visible = True celllabel.Visible = True studentidlabel.Visible = True EditStudentToolStripMenuItem.Enabled = True fnametxtbox.Enabled = False fnametxtbox.Visible = True fnametxtbox.BorderStyle = BorderStyle.FixedSingle fnametxtbox.TabStop = True fnametxtbox.TabIndex = 1 fnametxtbox.BackColor = Color.White fnametxtbox.ForeColor = Color.Black mnametxtbox.Enabled = False mnametxtbox.Visible = True mnametxtbox.BorderStyle = BorderStyle.FixedSingle mnametxtbox.TabStop = True mnametxtbox.TabIndex = 2 mnametxtbox.BackColor = Color.White mnametxtbox.ForeColor = Color.Black lnametxtbox.Enabled = False lnamelabel.Visible = True lnametxtbox.BorderStyle = BorderStyle.FixedSingle lnametxtbox.TabStop = True lnametxtbox.TabIndex = 3 lnametxtbox.BackColor = Color.White lnametxtbox.ForeColor = Color.Black addresstxtbox.Enabled = False addresstxtbox.Visible = True addresstxtbox.BorderStyle = BorderStyle.FixedSingle addresstxtbox.TabStop = True addresstxtbox.TabIndex = 4 addresstxtbox.BackColor = Color.White addresstxtbox.ForeColor = Color.Black address2txtbox.Enabled = False address2txtbox.Visible = True address2txtbox.BorderStyle = BorderStyle.FixedSingle address2txtbox.TabStop = True address2txtbox.TabIndex = 5 address2txtbox.BackColor = Color.White address2txtbox.ForeColor = Color.Black citytxtbox.Enabled = False citytxtbox.Visible = True citytxtbox.BorderStyle = BorderStyle.FixedSingle citytxtbox.TabStop = True citytxtbox.TabIndex = 6 citytxtbox.BackColor = Color.White citytxtbox.ForeColor = Color.Black statetxtbox.Enabled = False statetxtbox.Visible = True statetxtbox.BorderStyle = BorderStyle.FixedSingle statetxtbox.TabStop = True statetxtbox.TabIndex = 7 statetxtbox.BackColor = Color.White statetxtbox.ForeColor = Color.Black ziptxtbox.Enabled = False ziptxtbox.Visible = True ziptxtbox.BorderStyle = BorderStyle.FixedSingle ziptxtbox.TabStop = True ziptxtbox.TabIndex = 8 ziptxtbox.BackColor = Color.White ziptxtbox.ForeColor = Color.Black countrytxtbox.Enabled = False countrytxtbox.Visible = True countrytxtbox.BorderStyle = BorderStyle.FixedSingle countrytxtbox.TabStop = True countrytxtbox.TabIndex = 9 countrytxtbox.BackColor = Color.White countrytxtbox.ForeColor = Color.Black celltxtbox.Enabled = False celltxtbox.Visible = True celltxtbox.BorderStyle = BorderStyle.FixedSingle celltxtbox.TabStop = True celltxtbox.TabIndex = 10 celltxtbox.BackColor = Color.White celltxtbox.ForeColor = Color.Black studentidtxtbox.Enabled = False studentidtxtbox.Visible = True studentidtxtbox.BorderStyle = BorderStyle.FixedSingle studentidtxtbox.TabStop = True studentidtxtbox.TabIndex = 11 studentidtxtbox.BackColor = Color.White studentidtxtbox.ForeColor = Color.Black fnamelabel.Visible = True mnamelabel.Visible = True lnamelabel.Visible = True addressstreetlabel.Visible = True address2label.Visible = True addresscitylabel.Visible = True addressstatelabel.Visible = True addressziplabel.Visible = True addresscountrylabel.Visible = True celllabel.Visible = True studentidlabel.Visible = True End If For Each DataRow In dt.Rows If stunumtxtbox.Text = dt.Rows(0)("studentId").ToString Then fnametxtbox.Text = dt.Rows(0)("firstName").ToString mnametxtbox.Text = dt.Rows(0)("midleInitial").ToString lnametxtbox.Text = dt.Rows(0)("lastName").ToString addresstxtbox.Text = dt.Rows(0)("addressStreet").ToString address2txtbox.Text = dt.Rows(0)("addressOption").ToString citytxtbox.Text = dt.Rows(0)("addressCity").ToString statetxtbox.Text = dt.Rows(0)("addressState").ToString ziptxtbox.Text = dt.Rows(0)("addressZip").ToString countrytxtbox.Text = dt.Rows(0)("addressCountry").ToString celltxtbox.Text = dt.Rows(0)("contactcellphone").ToString studentidtxtbox.Text = dt.Rows(0)("studentId").ToString StudentNameTextBox.Text = lnametxtbox.Text + "," + " " + fnametxtbox.Text + " " + mnametxtbox.Text Else fnamelabel.Visible = False mnamelabel.Visible = False lnamelabel.Visible = False addressstreetlabel.Visible = False address2label.Visible = False addresscitylabel.Visible = False addressstatelabel.Visible = False addressziplabel.Visible = False addresscountrylabel.Visible = False celllabel.Visible = False studentidlabel.Visible = False End If Next End Using Catch se As SqlException MsgBox(se.Message) Finally End Try End If stunumtxtbox.Clear() stunumtxtbox.Select() End Sub ```
Some simplification of your work. If your datatable has no rows then you have no matches. ``` Dim count = da.Fill(dt) If count = 0 then ' you have no matches ' do you logic for no matches here Else ' fill data fnametxtbox.Text = dt.Rows(0)("firstName").ToString mnametxtbox.Text = dt.Rows(0)("midleInitial").ToString lnametxtbox.Text = dt.Rows(0)("lastName").ToString addresstxtbox.Text = dt.Rows(0)("addressStreet").ToString address2txtbox.Text = dt.Rows(0)("addressOption").ToString citytxtbox.Text = dt.Rows(0)("addressCity").ToString statetxtbox.Text = dt.Rows(0)("addressState").ToString ziptxtbox.Text = dt.Rows(0)("addressZip").ToString countrytxtbox.Text = dt.Rows(0)("addressCountry").ToString celltxtbox.Text = dt.Rows(0)("contactcellphone").ToString studentidtxtbox.Text = dt.Rows(0)("studentId").ToString End If ``` `Try/Catches` are for things that may explode, how will this explode? Simple concatenating should not need a `Try/Catch`. And we use `&` in VB for concatenating. The outer one will not catch all exceptions since you narrowed it's catch ability to `SqlException` only. ``` Try StudentNameTextBox.Text = lnametxtbox.Text + "," + " " + fnametxtbox.Text + " " + mnametxtbox.Text Catch ex As Exception MsgBox(ex.Message) ```
Searching SQL via Windows Form
[ "", "sql", "vb.net", "visual-studio", "" ]
I am looking for a free SQL database able to handle my data model. The project is a production database working in a local network not connected to the internet without any replication. The number of application connected at the same times would be less than 10. The data volume forecast for the next 5 years are: * 3 tables of 100 millions rows * 2 tables of 500 millions rows * 20 tables with less than 10k rows My first idea was to use MySQL, but I have found around the web [several articles](http://www.datastax.com/wp-content/uploads/2012/08/WP-DataStax-MySQLtoCassandra.pdf) saying that MySQL is not designed for big database. But, what is the meaning of **big** in this case? Is there someone to tell me if MySQL is able to handle my data model? I read that Postgres would be a good alternative, but require a lot of hours for tuning to be efficient with big tables. I don't think so that my project would use NOSQL database. I would know if someone has some experience to share with regarding MySQL. **UPDATE** The database will be accessed by C# software (max 10 at the same times) and web application (2-3 at the same times), It is important to mention that only **few update will be done on the big tables**, only insert query. Delete statements will be only done few times on the 20 small tables. The big tables are very often used for select statement, but the most often in the way to know if an entry exists, not to return grouped and ordered batch of data.
I work for Percona, a company that provides consulting and other services for MySQL solutions. For what it's worth, we have worked with [many customers](http://www.percona.com/about-us/customers) who are successful using MySQL with very large databases. Terrabytes of data, tens of thousands of tables, tables with billions of rows, transaction load of tens of thousands of requests per second. You may get some more insight by reading some of our [customer case studies](http://www.percona.com/resources/mysql-case-studies). You describe the number of tables and the number of rows, but nothing about how you will query these tables. Certainly one could query a table of only a few hundred rows in a way that would not scale well. But this can be said of any database, not just MySQL. Likewise, one could query a table that is terrabytes in size in an efficient way. It all depends on how you need to query it. You also have to set specific goals for performance. If you want queries to run in milliseconds, that's challenging but doable with high-end hardware. If it's adequate for your queries to run in a couple of seconds, you can be a lot more relaxed about the scalability. The point is that MySQL is not a constraining factor in these cases, any more than any other choice of database is a constraining factor. --- Re your comments. MySQL has [referential integrity checks](https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html) in its default storage engine, InnoDB. The claim that "MySQL has no integrity checks" is a myth often repeated over the years. I think you need to stop reading superficial or outdated articles about MySQL, and read some more complete and current documentation. * [MySQLPerformanceBlog.com](http://mysqlperformanceblog.com/) * [High Performance MySQL, 3rd edition](http://shop.oreilly.com/product/0636920022343.do) * [MySQL 5.6 manual](http://dev.mysql.com/doc/refman/5.6/en/)
MySQL has a two important (and significantly different) database engines - MyISAM and InnoDB. A limits depends on usage - MyISAM is nontransactional - there is relative fast import, but it is too simple (without own memory cache) and JOINs on tables higher than 100MB can be slow (due too simple MySQL planner - hash joins is supported from 5.6). InnoDB is transactional and is very fast on operations based on primary key - but import is slower. Current versions of MySQL has not good planner as Postgres has (there is progress) - so complex queries are usually much better on PostgreSQL - and really simple queries are better on MySQL. Complexity of PostgreSQL configuration is myth. It is much more simple than MySQL InnoDB configuration - you have to set only five parameters: max\_connection, shared\_buffers, work\_mem, maintenance\_work\_mem and effective\_cache\_size. Almost all is related to available memory for Postgres on server. Usually work for 5 minutes. On my experience a databases to 100GB is usually without any problems on Postgres (probably on MySQL too). There are two important factors - how speed you expect and how much memory and how fast IO you have. With large databases you have to have a experience and knowledges for any database technology. All is fast when you are in memory, and when ratio database size/memory is higher, then much more work you have to do to get good results.
What data quantity is considered as too big for MySQL?
[ "", "mysql", "sql", "database", "postgresql", "" ]
I have a table with a column of floats. All the time that I need a median (or first quartile, for example) I have to compute it first and in other query I compute average, total sum, number of records, etc... (all together). My question is: Is there a way to compute median, average, total sum,... in the same query?
You can do the following in SQL Server 2005 and upwards: ``` SELECT AVG(Salary) as AVERAGE, MAX(case when seqnum = cnt / 2 then salary end) as median, MAX(SALARY) as MAXIMUM, MIN(SALARY) as MINIMUM, SUM(SALARY) as TOTAL, TOTAL as NUMBER_OF_EMP FROM (SELECT e.*, count(*) over () as total, row_number() over (order by salary) as seqnum FROM TblEmployees e ) e ```
I have found this function in SQL Server 2012 that does what I want: <http://technet.microsoft.com/en-us/library/hh231327.aspx> I couldn't solve the problem in just one query but it is more clean than the option I had before. Look this functional example: [SQLFIDDLE](http://sqlfiddle.com/#!6/36e2e6/18/0) Supose I have a table of remuneration of employees, I could use the function as: ``` SELECT AVG(Salary) MEAN, MAX(MEDIAN) MEDIAN, MAX(SALARY) MAXIMUM, MIN(SALARY) MINIMUM, SUM(SALARY) TOTAL, COUNT(*) NUMBER_OF_EMP FROM ( SELECT *, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY Salary) OVER() MEDIAN FROM TblEmployees ) A ```
Calculating median in the same query
[ "", "sql", "sql-server", "" ]
What is the good approach to keep a `nvarchar` field unique. I have a field which is storing URLs of MP3 files. The URL length can be anything from 10 characters to 4000. I tried to create an index and it says it cannot create the index as the total length exceeds 900 bytes. If the field is not indexed, it's going to be slow to search anything. I am using C#, ASP.net MVC for the front end.
You could use CHECKSUM command and put index on column with checksum. ``` --*** Add extra column to your table that will hold checksum ALTER TABLE Production.Product ADD cs_Pname AS CHECKSUM(Name); GO --*** Create index on new column CREATE INDEX Pname_index ON Production.Product (cs_Pname); GO ``` Then you can retrieve data fast using following query: ``` SELECT * FROM Production.Product WHERE CHECKSUM(N'Bearing Ball') = cs_Pname AND Name = N'Bearing Ball'; ``` Here is the documentation: <http://technet.microsoft.com/en-us/library/ms189788.aspx>
You can use a hash function (although theoretically it doesn't guarantee that two different titles will have different hashes, but should be good enough: [MD5 Collisions](https://stackoverflow.com/questions/201705/how-many-random-elements-before-md5-produces-collisions)) and then apply the index on that column. [MD5 in SQL Server](https://stackoverflow.com/questions/3525997/generate-md5-hash-string-with-t-sql)
Sql Server - Index on nvarchar field
[ "", "sql", "sql-server", "nvarchar", "" ]
My current table looks like this: ``` ID TYPE QUANTITY 1 A1 3 2 B1 2 3 A1 2 4 B1 8 ``` And after doing the query I want to get that: ``` ID TYPE QUANTITY SUM 1 A1 3 5 2 B1 2 10 3 A1 2 5 4 B1 8 10 ``` The SUM column consist of summed quantities of items with the same type.
``` SELECT t.ID,t.TYPE,t.QUANTITY,x.SUM FROM TABLE t LEFT JOIN (SELECT ID,TYPE,QUANTITY,SUM(QUANTITY) AS SUM FROM TABLE GROUP BY TYPE)x ON t.type=x.type ``` [**SQL Fiddle**](http://sqlfiddle.com/#!2/b6d4e/6)
My approach is to use a derived table which aggregates the quantity by type first and then join this result with the original data: ``` select t.id, t.type, t.quantity, tmp.overall from table t join ( select table.type, sum(table.quantity) as overall from table group by table.type ) tmp on t.type = tmp.type ```
SQL, add column with summed values of the same type
[ "", "mysql", "sql", "" ]
For the DB gurus out there, I was wondering if there is any functional/performance difference between Joining to the results a SELECT statement and Joining to a previously filled table variable. I'm working in SQL Server 2008 R2. Example (TSQL): ``` -- Create a test table DROP TABLE [dbo].[TestTable] CREATE TABLE [dbo].[TestTable]( [id] [int] NOT NULL, [value] [varchar](max) NULL ) ON [PRIMARY] -- Populate the test table with a few rows INSERT INTO [dbo].[TestTable] SELECT 1123, 'test1' INSERT INTO [dbo].[TestTable] SELECT 2234, 'test2' INSERT INTO [dbo].[TestTable] SELECT 3345, 'test3' -- Create a reference table DROP TABLE [dbo].[TestRefTable] CREATE TABLE [dbo].[TestRefTable]( [id] [int] NOT NULL, [refvalue] [varchar](max) NULL ) ON [PRIMARY] -- Populate the reference table with a few rows INSERT INTO [dbo].[TestRefTable] SELECT 1123, 'ref1' INSERT INTO [dbo].[TestRefTable] SELECT 2234, 'ref2' -- Scenario 1: Insert matching results into it's own table variable, then Join -- Create a table variable DECLARE @subset TABLE ([id] INT NOT NULL, [refvalue] VARCHAR(MAX)) INSERT INTO @subset SELECT * FROM [dbo].[TestRefTable] WHERE [dbo].[TestRefTable].[id] = 1123 SELECT t.*, s.* FROM [dbo].[TestTable] t JOIN @subset s ON t.id = s.id -- Scenario 2: Join directly to SELECT results SELECT t.*, s.* FROM [dbo].TestTable t JOIN (SELECT * FROM [dbo].[TestRefTable] WHERE id = 1123) s ON t.id = s.id ``` In the "real" world, the tables and table variable are pre-defined. What I'm looking at is being able to have the matched reference rows available for further operations, but I'm concerned that the extra steps will slow the query down. Are there technical reasons as to why one would be faster than the other? What sort of performance difference may be seen between the two approaches? I realize it is difficult (if not impossible) to give a definitive answer, just looking for some advice for this scenario.
The database engine has an optimizer to figure out the best way to execute a query. There is more under the hood than you probably imagine. For instance, when SQL Server is doing a join, it has a choice of at least four join algorithms: * Nested Loop * Index Lookup * Merge Join * Hash Join (not to mention the multi-threaded versions of these.) It is not important that you understand how each of these works. You just need to understand two things: different algorithms are best under different circumstances and SQL Server does its best to choose the best algorithm. The choice of join algorithm is only one thing the optimizer does. It also has to figure out the ordering of the joins, the best way to aggregate results, whether a sort is needed for an `order by`, how to access the data (via indexes or directly), and much more. When you break the query apart, you are making an assumption about optimization. In your case, you are making the assumption that the first best thing is to do a select on a particular table. You might be right. If so, your result with multiple queries should be about as fast as using a single query. Well, maybe not. When in a single query, SQL Server does not have to buffer all the results at once; it can stream results from one place to another. It may also be able to take advantage of parallelism in a way that splitting the query prevents. In general, the SQL Server optimizer is pretty good, so you are best letting the optimizer do the query all in one go. There are definitely exceptions, where the optimizer may not choose the best execution path. Sometimes fixing this is as easy as being sure that statistics are up-to-date on tables. Other times, you can add optimizer hints. And other times you can restructure the query, as you have done. For instance, one place where loading data into a local table is useful is when the table comes from a different server. The optimizer may not have full information about the size of the table to make the best decisions. In other words, keep the query as one statement. If you need to improve it, then focus on optimization after it works. You generally won't have to spend much time on optimization, because the engine is pretty good at it.
This would give the same result? ``` SELECT t.*, s.* FROM dbo.TestTable AS t JOIN dbo.TestRefTable AS s ON t.id = s.id AND s.id = 1123 ``` Basically, this is a cross join of all records from `TestTable` and `TestRefTable` with `id = 1123`.
Join to SELECT vs. Join to Tableset
[ "", "sql", "sql-server", "performance", "t-sql", "database-performance", "" ]
I have a table with approx 100,000 rows per day, each containing the date they were added. However, rows are only added on business days, so no weekends or bank holidays. I'm trying to find an efficient way to find the `Max(BusinessDate)` and also the next highest `max(BusinessDate)`. However, when I try the following it takes 20 mins to run (+50Mn rows total). ``` SELECT MAX(t1.BusinessDataDate) AS BusinessDataDate , MAX(t2.BusinessDataDate) AS PreviousDataDate FROM cb_account t1 , cb_account t2 WHERE t2.BusinessDataDate < t1.BusinessDataDate ``` Just selecting the `Max(BusinessDataDate)` is instant. ``` SELECT TOP 2 'cb_account' AS TableName , BusinessDataDate FROM cb_account GROUP BY BusinessDataDate ORDER BY BusinessDataDate DESC ``` will give me both the dates, but I really need them in a single row.
``` SELECT MAX(dates.BusinessDataDate) AS BusinessDataDate, MIN(dates.BusinessDataDate) AS PreviousDataDate FROM (SELECT TOP 2 'cb_account' AS TableName , BusinessDataDate FROM cb_account GROUP BY BusinessDataDate ORDER BY BusinessDataDate DESC) dates ```
If I've got it right try this: ``` WITH T as ( SELECT MAX(BusinessDataDate) as MaxD FROM cb_account ) SELECT MaxD, (SELECT MAX(BusinessDataDate) FROM cb_account WHERE BusinessDataDate<T.MaxD) FROM T ```
Select Max(Date) and next highest Max(date) from table
[ "", "sql", "sql-server", "query-optimization", "" ]
I have the following data: ``` Server AvgValue Server1 1.29 Server2 0.2 Server3 1.74 Server4 0.58 Server5 2.06 Server6 2.82 ``` I'd like to show the count of servers that have an: 1. AvgValue < 10 2. AvgValue > 10 and < 30 3. AvgValue > 30 and < 50 4. AvgValue > 50 and < 80 5. AvgValue > 80 Any suggestions? --- Alberto has provided the best option so far, and does answer my original question. I am however running into cases where the server is listed multiple times, and I'd like to average the AvgValue and make sure the server is only counted once in the range. Thoughts?
I think the most simple approach is to use a query like this: ``` SELECT Server, COUNT(*) AS ServersCount FROM ServersTable WHERE AvgValue < 10 GROUP BY Server ``` You didn't mention anything about the RDBMS that you're using. If you're using MySQL, check the documentation about [COUNT()](https://dev.mysql.com/doc/refman/5.1/en/counting-rows.html). This query has to be modified for each condition. Then, you will have to execute five different queries. Otherwise, you can use the following query: ``` SELECT ServersWithAvgValueLT10 = SUM(CASE WHEN AvgValue < 10 THEN 1 ELSE 0 END), ServersWithAvgValueGT10LT30 = SUM(CASE WHEN AvgValue > 10 AND AvgValue < 30 THEN 1 ELSE 0 END), ServersWithAvgValueGT30LT50 = SUM(CASE WHEN AvgValue > 30 AND AvgValue < 50 THEN 1 ELSE 0 END), ServersWithAvgValueGT50LT80 = SUM(CASE WHEN AvgValue > 50 AND AvgValue < 80 THEN 1 ELSE 0 END), ServersWithAvgValueGT80 = SUM(CASE WHEN AvgValue > 80 THEN 1 ELSE 0 END), FROM ServersTable ``` The result is achieved using the [SUM](https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_sum) function and [CASE](https://dev.mysql.com/doc/refman/5.0/en/case.html) statement.
You can do it in a single query like ``` select server, count(Server) as NUmber_Of_Server, sum(floor(AvgValue)) as Avg_Score from tab group by Server ``` See a demo fiddle here <http://sqlfiddle.com/#!2/0e05e/5>
Count Rows Under Within Specific Ranges
[ "", "sql", "" ]
I have to find how many times a user appears in two different tables ... for now I used a union I have this Query And I Want to do A `SUM` of my record ``` (SELECT s.proprietario_id as p, COUNT(*) as conta FROM sn_like_spotted s GROUP BY s.proprietario_id ORDER BY COUNT(*) DESC, s.id ASC ) UNION ALL (SELECT s.proprietario_id as p, COUNT(*) as conta2 FROM sn_like_risposta s GROUP BY s.proprietario_id ORDER BY COUNT(*) DESC, s.id ASC ) ``` My result: ``` p conta 1 33 2 15 3 1 4 11 5 2 1 20 2 9 4 2 9 2 18 5 19 7 ``` And I Want the p with max Sum of conta The result should be ``` p conta 1 53 2 24 4 13 19 7 ... ```
Use a subquery! ``` SELECT p, SUM(conta) AS conta FROM ( SELECT s.proprietario_id as p, COUNT(*) as conta FROM sn_like_spotted s GROUP BY s.proprietario_id UNION ALL SELECT s.proprietario_id as p, COUNT(*) as conta2 FROM sn_like_risposta s GROUP BY s.proprietario_id ) AS baseview GROUP BY p ORDER BY conta DESC, p ASC ``` **EDIT** I cust/pasted your original query, which produced bad ordering - fixed now.
I don't know mySQL but don't you want to union the results set together and then to do the group by? Conceptually somthing like ``` SELECT s.proprietario_id as p, COUNT(*) as conta from ((SELECT s.proprietario_id as p FROM sn_like_spotted s ) UNION ALL (SELECT s.proprietario_id as p FROM sn_like_risposta s )) GROUP BY s.proprietario_id ORDER BY COUNT(*) DESC, s.id ASC ```
Sum Union Mysql
[ "", "mysql", "sql", "" ]
I have here a complicated query here where I have nested case with subquery. I am having trouble with getting the right structure of it. Here is my code: ``` select AccountNo, Case when Datepart (month,TranDate) = 1 Then Case ISNULL(RemainingBalance,'NULLVALUE') When 'NULLVALUE' Then (select top 1 RemainingBalance From tempAccountBalance where DATEPART (YEAR,TranDate)=@FiscalYear-1 order by TranDate desc) else MIN(Case when Datepart (month,TranDate) <= 3 Then RemainingBalance END) End Q1 FROM tempAccountBalance WHERE Datepart (year,TranDate) = @FiscalYear and AccountNo=@AccountNo Group By AccountNo ``` I get an error which says, `Msg 102, Level 15, State 1, Line 11 Incorrect syntax near 'Q1'.`
If you indent your code, you'll spot errors like this more easily (below). Note however that your query still has grouping issues - you'll either need to add `TranDate` and `RemainingBalance` to the `GROUP BY`, or use aggregates on them. I've taken a guess below without any understanding of your query: ``` select AccountNo, Case when Datepart(month,TranDate) = 1 Then Case ISNULL(Min(RemainingBalance), 'NULLVALUE') -- Added Min When 'NULLVALUE' Then (select top 1 RemainingBalance From tempAccountBalance where DATEPART (YEAR,TranDate)=@FiscalYear-1 order by TranDate desc) else MIN( Case when Datepart (month,TranDate) <= 3 Then RemainingBalance END) end -- Missing End Q1 FROM tempAccountBalance WHERE Datepart(year,TranDate) = @FiscalYear and AccountNo=@AccountNo Group By AccountNo, Datepart(month,TranDate); -- Added to Group By ```
You need an `END` before the Q1 : ``` select AccountNo, Case when Datepart (month,TranDate) = 1 Then Case ISNULL(RemainingBalance,'NULLVALUE') When 'NULLVALUE' Then (select top 1 RemainingBalance From tempAccountBalance where DATEPART (YEAR,TranDate)=@FiscalYear-1 order by TranDate desc) else MIN(Case when Datepart (month,TranDate) <= 3 Then RemainingBalance END) End End Q1 FROM tempAccountBalance WHERE Datepart (year,TranDate) = @FiscalYear and AccountNo=@AccountNo Group By AccountNo ```
What is the proper structure for Nested Case statement with Subquery Sql Statement?
[ "", "sql", "sql-server", "nested", "subquery", "case", "" ]
Which is intended to fetch the results quicker ? *Single column data* from 400 tables or 400 columns from a *single table* ?
400 results from one table is definitely faster than 1 result from each of the 400 tables. Think about needing to enter the first 400 phone numbers from the NYC phone book. So you decide to read the first number from phonebook A, the second number from phonebook B, ... , and the last number from the 400th phonebook. It would have been much faster to read them sequentially from the first phonebook (AKA structure your tables appropriately from the get-go). This is a major problem which will come back and bite many programmers. It comes down to the importance of strategically organizing the structure and layout of your data tables before you get in too deep.
As per my Knowledge fetching data from single table will be faster. If you are fetching data from single table you do not need to specify any joining condition. If you are having any situation where you want to fetch data from single column you can use the [ColumnStoreIndex](http://blog.aspplatinum.com/) feature of SQL Server 2012. But I am not sure that this type of indexing is available in mySql or not. Basically I have posted here the concept of MS SQL server. I am not having much idea about MySQL.
Which is intended to fetch the results quicker?
[ "", "mysql", "sql", "database", "" ]
I have the following SQL Query that counts Orders and groups them by each Day (Date). Thus the following results: ``` 01/02/2014 = 10 02/02/2014 = 2 05/02/2014 = 7 07/02/2014 = 4 ``` Query: ``` SELECT TOP(@NumberOfRecords) DATEADD(dd, 0, DATEDIFF(dd, 0, AddedDate)) AS Date, COUNT(DISTINCT ID) AS Count FROM OrderSpecs GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, AddedDate)) ORDER BY Date DESC ``` My question is, how can I get my Query to fill in any of the in-between missing dates and set the Count value to 0? Example Desired Results: ``` 01/02/2014 = 10 02/02/2014 = 2 03/02/2014 = 0 04/02/2014 = 0 05/02/2014 = 7 06/02/2014 = 0 07/02/2014 = 4 ``` Many thanks for you time taken out to read this.
``` DECLARE @mindate DATETIME DECLARE @maxdate DATETIME DECLARE @diff INT SELECT @maxdate = MAX(addeddate), @mindate = MIN(addeddate) FROM OrderSpecs SET @diff = DATEDIFF(DAY, @mindate,@maxdate) ;WITH cte(dt,level) AS ( SELECT @mindate AS dt, 0 AS level UNION ALL SELECT DATEADD(day,1,cte.dt),level + 1 from cte WHERE level < @diff ) SELECT dt,c FROM cte LEFT JOIN ( SELECT DATEADD(dd, 0, DATEDIFF(dd, 0,AddedDate)) AddedDt, COUNT(ID) AS c FROM OrderSpecs GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0,AddedDate)) ) tab ON cte.dt = tab.AddedDt OPTION (MaxRecursion 32767); ``` CTE is written to generate all dates in a date range. With this a `LEFT JOIN` of aggregation resultset is done. Disclaimer: this query would not work if the date range is more that 32767 days
If you issue a lot of such queries then you can create a calendar table that contain all calendar dates ``` CREATE TABLE calendar([date] DATE NOT NULL PRIMARY KEY); ``` And then use an outer join ``` SELECT TOP(@NumberOfRecords) c.Date, COALESCE(o.Count, 0) Count FROM Calendar c LEFT JOIN ( SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, AddedDate)) AS Date, COUNT(DISTINCT ID) AS Count FROM OrderSpecs GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, AddedDate)) ) o ON c.Date = o.Date ORDER BY Date DESC ``` Output: ``` | DATE | COUNT | |------------|-------| | 2014-02-07 | 4 | | 2014-02-06 | 0 | | 2014-02-05 | 7 | | 2014-02-04 | 0 | | 2014-02-03 | 0 | | 2014-02-02 | 2 | | 2014-02-01 | 10 | ``` Here is **[SQLFiddle](http://sqlfiddle.com/#!3/551ff/1)** demo
SQL Count Records, Group By Date and fill in missing date?
[ "", "sql", "" ]
I have a Query which gets the **average score** from the **answers** table, And groups it by the category which the question is in. This query gets the desired result for answers **where the coach\_id = 0** This is the desired result in which for every coach\_id i get another row ![enter image description here](https://i.stack.imgur.com/5xQun.png) **Now my question is:** Is it possible to also get the same answers from the same table ( so almost the same query ) but where the coach\_id = 1 or coach\_id = 2.. in the same query?## This is my query ``` SELECT ROUND((SUM(score) / COUNT(vragen.id) * 10),1) as score FROM antwoorden JOIN vragen ON vragen.id = antwoorden.vraag_id JOIN categorieen ON categorieen.id = vragen.categorie_id WHERE antwoorden.werknemer_id = 105 AND antwoorden.coach_id = 0 GROUP BY categorieen.id ``` Any ideas? Thanks!
What you want is a conditional sum, I think. Column score\_0, that gets the average score for coach\_id = 0. Column score\_1, that gets the average score for coach\_id = 1. The count will not work neither, as count ... counts everything! Both coach\_id 0 and 1. So you'll have to use a conditional sum there, too. Besides you'll need the coach\_id filter suggested by Neville K. So: ``` SELECT ROUND(( SUM(CASE WHEN antwoorden.coach_id = 0 THEN score ELSE 0 END) / SUM(CASE WHEN antwoorden.coach_id = 0 THEN 1 ELSE 0 END) * 10 ), 1) as score_0, ROUND(( SUM(CASE WHEN antwoorden.coach_id = 1 THEN score ELSE 0 END) / SUM(CASE WHEN antwoorden.coach_id = 1 THEN 1 ELSE 0 END) * 10 ), 1) as score_1 FROM antwoorden JOIN vragen ON vragen.id = antwoorden.vraag_id JOIN categorieen ON categorieen.id = vragen.categorie_id WHERE antwoorden.werknemer_id = 105 AND antwoorden.coach_id IN (0,1) GROUP BY categorieen.id ``` I think this is what you meant.
Since you haven't provided your table schemas I would have a hard time writing the query for your actual example. What you want is the `SUM(IF(...))` pattern, aggregating on a conditional: ``` SELECT foo_id, SUM(IF(bar_id = 1, baz, 0)) as sum_baz_bar_1, SUM(IF(bar_id = 2, baz, 0)) as sum_baz_bar_2, SUM(IF(bar_id = 3, baz, 0)) as sum_baz_bar_3 FROM table WHERE ... GROUP BY foo_id ``` You need to think carefully about your aggregation functions when using this pattern, especially with `COUNT` or other functions that deal with the presence of a value (such as `0`) rather than the value of it. If you post your table schemas (`SHOW CREATE TABLE`) or even better set up a sample data set on [sqlfiddle.com](http://sqlfiddle.com), I would be happy to help show how to do it with your actual schemas.
One query for multiple where?
[ "", "mysql", "sql", "" ]
I have a table which amongst other things contains a DateTime column. What is the best way to get the maximum number of rows within x seconds of each other? So if I have the following rows: ``` 1 2014-02-09 01:01:01 2 2014-02-09 01:01:02 3 2014-02-09 01:01:03 4 2014-02-09 01:05:01 5 2014-02-09 01:05:11 6 2014-02-09 01:05:12 7 2014-02-09 01:05:23 8 2014-02-09 01:05:30 9 2014-02-09 01:05:45 10 2014-02-09 01:05:56 ``` How can I get the maximum number of rows within x number of seconds of each other? I.e. If I specified 10 seconds then it would return 3 because rows 1,2 and 3 are within 10 seconds of each other. If I was to specify 60 seconds then it would return 7 (rows 3 to 10?) Thanks, Joe
This query seems to do the job (for TSQL) ``` WITH CTE AS ( SELECT Id, value, CNT.X FROM tbl T1 OUTER APPLY ( SELECT COUNT(*) X FROM tbl T2 WHERE Datediff(second, T1.value, T2.value) BETWEEN 0 AND 10 ) CNT ) SELECT MAX(X) FROM CTE ``` Here is a fiddle that will show only the CTE itself (with the count for each row): <http://sqlfiddle.com/#!6/1a323/12>
You didn't specify which DBMS you're using. This Standard SQL should run (almost) everywhere, you just have to modify how add seconds to a timestamp: ``` SELECT MAX(cnt) FROM ( SELECT Id, value, (SELECT COUNT(*) FROM tbl t2 WHERE t2.value BETWEEN t1.value AND t1.value + INTERVAL '10' SECOND) AS cnt FROM tbl AS t1 ) AS dt ``` Performance should be similar to KekuSemau's query. And if you got luck your DBMS supports Windowed Aggregate Function using RANGE (e.g. Oracle), this should run faster: ``` SELECT MAX(cnt) FROM ( SELECT Id, value, COUNT(*) OVER (ORDER BY value RANGE BETWEEN CURRENT ROW AND INTERVAL '10' SECOND FOLLOWING) AS cnt FROM tbl AS t1 ) AS dt ```
SQL Get maximum number rows where DateTime is within x seconds
[ "", "sql", "" ]
I've got a bit of code that I'm looking at the moment : ``` User.includes([:profile => :schedule]).where('...') ``` This loads all profiles and their schedules. So the query produced by this is select \* user fields, select \* profile fields, select \* schedule fields I'm filtering out users based on one field from profile and based on one field from profiles schedule but this above statement is selecting all the fields from all of these. So I tried to do it with joins : ``` User.joins(:profile).joins('profiles.schedule').where('....').select('....') ``` This is throwing out error. I'm a former Java developer, still learning the rails stuff.
This should work: ``` User.joins(profile: :schedule).where('....').select('....') ```
Try this: ``` User.joins(profile: [:schedule]).where('...') ``` or ``` User.joins(profile: :schedule).where('...') ```
How to join more than one table rails
[ "", "sql", "ruby-on-rails", "ruby", "postgresql", "" ]
I am using SSIS package to import data from cvs file to table. ``` CVS File Report_Date 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 20140125 ``` I want to convert in to 2014-02-05 date format.How can i do that in ssis Package.I tried with convert and casting but i was not successfull.Can any one help me ?
You can use `CONVERT(` function to change that into date. For example ``` SELECT CONVERT(DATE,'20140210',112) ``` After you change it into date you can output it into any format that you want. Read <http://msdn.microsoft.com/en-us/library/ms187928.aspx> for list of all styles that you can use for `DATE` when converting it. `112` stands for `yyyymmdd` format. if date is stored as Numeric field you will need to convert it to VARCHAR before converting it to DATE, ``` SELECT CONVERT(DATE,CONVERT(VARCHAR(10),20140204),112) ```
I have not tested it with SSIS but if you look at TSQL output of these queries ``` Select Cast(20140125 AS DATETIME) Select Cast('20140125' AS DATETIME) ``` First one failed with "Arithmetic overflow error converting expression to data type datetime." But second succeed.. It means if you convert first it to string and then to DateTime, it should work.. Will update you if able to do directly from SSIS
Date format conversion of cvs column to table column using SSIS Package?
[ "", "sql", "t-sql", "ssis", "sql-server-2012", "dataflow", "" ]
I am getting the following error while trying to configure FileStream in SQL server 2012. **There was an unknown error applying the filestream settings. check the parameters are valid. (0x80041008)** I am configuring it using SQL server configuration manager. Where as I am able to setup it for SQL server 2008 R2.
I had this same problem just yesterday. In my case it was because I had a 64-bit Windows and a 32-Bit SQL Server. You do not see the exact error, but if you try to do it with T-SQL, then the proper error comes up in SQL, telling you something about "WOW64" not supporting filestream. I just uninstalled and installed the right bit version of SQL, and all worked 100% again.
In my case the problem I was running the SQL Server **2014** configuration manager. While this usually shouldn't cause problems, in my case it did. Configuring FILESTREAM using the SQL Server *2012* configuration manager worked. If it still doesn't work, make sure you're up-to-date. SQL Server 2012 has received quite a lot of patches (SP2, SP3, and some updates).
There was an unknown error applying the filestream settings. check the parameters are valid
[ "", "sql", "sql-server", "sqlfilestream", "" ]
I have a table with the following: * eventid -> primary key, higher numbers mean newer * itemid -> foreign key to an items table * message -> event message There will be 100/1000s of events for each itemid. What I need is to get the X newest events from the table for every unique value of itemid. In this case X is 20 and "newest" is the highest eventid. What I was doing before is getting the entire table and only keeping the 20 newest for each itemid. This is very slow and inefficient. Edit: I'm using opennms and the Events table ([OpenNMS create.sql](http://sourceforge.net/p/opennms/svn/14491/tree//opennms/trunk/opennms-install/src/test/resources/etc/create.sql#l663)): (itemid == nodeID) ``` create table events ( eventID integer not null, eventUei varchar(256) not null, nodeID integer, eventTime timestamp with time zone not null, eventHost varchar(256), eventSource varchar(128) not null, ipAddr varchar(16), eventDpName varchar(12) not null, eventSnmphost varchar(256), serviceID integer, eventSnmp varchar(256), eventParms text, eventCreateTime timestamp with time zone not null, eventDescr varchar(4000), eventLoggroup varchar(32), eventLogmsg varchar(256), eventSeverity integer not null, eventPathOutage varchar(1024), eventCorrelation varchar(1024), eventSuppressedCount integer, eventOperInstruct varchar(1024), eventAutoAction varchar(256), eventOperAction varchar(256), eventOperActionMenuText varchar(64), eventNotification varchar(128), eventTticket varchar(128), eventTticketState integer, eventForward varchar(256), eventMouseOverText varchar(64), eventLog char(1) not null, eventDisplay char(1) not null, eventAckUser varchar(256), eventAckTime timestamp with time zone, alarmID integer, constraint pk_eventID primary key (eventID) ); ``` My query was very simple: ``` SELECT eventid, nodeid, eventseverity, eventtime, eventlogmsg FROM events WHERE nodeid IS NOT NULL; ```
If you want a fixed number of "latest" entries, you need to use the window function [row\_number()](http://www.postgresql.org/docs/current/interactive/functions-window.html) (not `rank()`). Although, if the `eventid` happens to be unique (per `itemid`), the only (slight) difference is performance. (Your question update confirms that.) Also, you need a subquery for this, since `WHERE` conditions are applied *before* window functions: ``` SELECT itemid, eventid, nodeid, eventseverity, eventtime, eventlogmsg FROM ( SELECT itemid, eventid, nodeid, eventseverity, eventtime, eventlogmsg ,row_number() OVER (PARTITION BY itemid ORDER BY eventid DESC NULLS LAST) AS rn FROM events WHERE nodeid IS NOT NULL ) sub WHERE rn <= 20 ORDER BY 1, 2 DESC NULLS LAST; ``` The [`NULLS LAST`](https://stackoverflow.com/questions/7621205/sort-null-values-to-the-end-of-a-table/7622046#7622046) clause is only relevant if `eventid` can be NULL, in which case this would sort rows with NULL values to the end. (Your question update rules that out, so the clause is not needed.)
I would imagine that it is quite expensive and there may be better ways, but would something like this work for you? ``` select itemid, message from events e where eventid in (select eventid from events f where e.itemid=f.itemid order by eventid desc limit 20) order by itemid ``` The subquery finds the most recent items for a particular itemid and the outer query does that for all items. There is a mockup in [sqlfiddle](http://sqlfiddle.com/#!15/a1221/1).
Select the X newest rows for each unique value of a column
[ "", "sql", "postgresql", "greatest-n-per-group", "window-functions", "" ]
This is my MySQL query: ``` SELECT ROUND(SUM(cfv.NUMBERVALUE),0) AS mysum FROM jissue ji JOIN customfieldvalue cfv ON ji.ID=cfv.ISSUE WHERE ji.pkey LIKE '%PB-%' AND cfv.customfield=11381 AND ji.issuestatus=10127; ``` There are two possible cfv.customfield (11381 and 11382) and five possible ji.issuestatus (10127 -> 10131), so I run the query ten times changing those two fields each time. Is it possible to compress this into one query that will return all ten SUMs? **EDIT: I would like the result to also include empty values.** Currently, only 8 rows are returned because ji.issuestatus=10128 has no NUMBERVALUE for 11381 and 11382. I would like the result to also include 10128 with empty values for 11381/2.
1. As said wumpz and Anthony Grist, you use `GROUP BY` to return all 2\*5 sums *without sums for missing entries*. 2. To return sums for missing entries, you use LEFT JOIN. Difference between `tableexpr1 JOIN tableexpr2 ON ...` and `tableexpr1 LEFT JOIN tableexpr2 ON ...` is with LEFT JOIN entries from tableexpr1 are output even when there are no corresponding entries in tableexpr2. ``` SELECT ji.issuestatus, cf.ID AS customfield_id, ROUND(SUM(cfv.NUMBERVALUE),0) AS mysum FROM jissue ji CROSS JOIN customfield cf LEFT JOIN customfieldvalue cfv ON cfv.ISSUE=ji.ID AND cfv.customfield=cf.ID WHERE ji.pkey LIKE '%PB-%' AND ji.issuestatus IN (10127,10128,10129,10130,10131) AND cf.ID IN IN (11381, 11382) GROUP BY ji.issuestatus, cf.ID; ```
Something like this: ``` SELECT cfv.customfield, ji.issuestatus, ROUND(SUM(cfv.NUMBERVALUE),0) AS mysum FROM jissue ji JOIN customfieldvalue cfv ON ji.ID=cfv.ISSUE WHERE ji.pkey LIKE '%PB-%' AND cfv.customfield IN (11381, 11382) AND ji.issuestatus IN (10127, 10128, ..., 10131) GROUP BY cfv.customfield, ji.issuestatus ``` The first two columns and the GROUP BY clause are there so that you have a sum for each of the ten different combinations, otherwise you're just going to have the sum of all rows that match any of the ten combinations.
Can I combine ten similar SQL queries to one?
[ "", "mysql", "sql", "" ]
Why Mysql's Group By and Oracle's Group by behaviours are different I found many times that Mysql's groupBy functionality and Oracle's GroupBy funcnality are behaving different Many times I found error in Oracle(which is actually wrong query) but Mysql will give result in to this so is there any reason behind this Mysql weird behavior
The MySQL designers put in their nonstandard extension to `GROUP BY` in an attempt to make development easier and certain queries more efficient. Here's their rationale. <https://dev.mysql.com/doc/refman/8.0/en/group-by-handling.html> There is a server mode called `ONLY_FULL_GROUP_BY` which disables the nonstandard extensions. You can set this mode using this statement. ``` SET SESSION SQL_MODE='ONLY_FULL_GROUP_BY' ``` Here's a quote from that page, with emphasis added. > If `ONLY_FULL_GROUP_BY` is disabled, a MySQL extension to the standard SQL use of `GROUP BY` permits the select list, `HAVING` condition, or `ORDER BY` list to refer to nonaggregated columns even if the columns are not functionally dependent on `GROUP BY` columns... In this case, the server is **free to choose any value from each group**, so unless they are the same, the values chosen are **nondeterministic**, which is probably not what you want. The important word here is **nondeterministic.** What does that mean? It means *random, but worse.* If the server chose random values, that implies it would return different values in different queries, so you have a chance of catching the problem when you test your software. But *nondeterministic* in this context means the server chooses the same value every time, *until it doesn't.* Why might it change the value it chooses? A server upgrade is one reason. A change to table size might be another. The point is, the server is free to return whatever value it wants. I wish people newly learning SQL would set this `ONLY_FULL_GROUP_BY` mode; they'd get much more predictable results from their queries, and the server would reject nondeterministic queries.
Oracle does not extend the older SQL Standard that states that all items in the select list not contained in an aggregate function must be included in the group by clause. The [MySQL Docs](https://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html) state: --- > In standard SQL, a query that includes a GROUP BY clause cannot refer to nonaggregated columns in the select list that are not named in the GROUP BY clause. For example, this query is illegal in standard SQL because the name column in the select list does not appear in the GROUP BY: ``` SELECT o.custid, c.name, MAX(o.payment) FROM orders AS o, customers AS c WHERE o.custid = c.custid GROUP BY o.custid; ``` > For the query to be legal, the name column must be omitted from the select list or named in the GROUP BY clause. > > MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. This means that the preceding query is legal in MySQL. You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. --- So to answer your question as to why MySQL does this the most pertinent extract is: > You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. I always advocate to steer clear of this particular MySQL extension unless you fully understand it. Imagine the following simple table (T): ``` ID | Column1 | Column2 | ----|---------+----------| 1 | A | X | 2 | A | Y | ``` In MySQL you can write ``` SELECT ID, Column1, Column2 FROM T GROUP BY Column1; ``` This actually breaks the SQL Standard, but it works in MySQL, however the trouble is it is non-deterministic, the result: ``` ID | Column1 | Column2 | ----|---------+----------| 1 | A | X | ``` Is no more or less correct than ``` ID | Column1 | Column2 | ----|---------+----------| 2 | A | Y | ``` So what you are saying is give me one row for each distinct value of `Column1`, which both results sets satisfy, so how do you know which one you will get? Well you don't, it seems to be a fairly popular misconception that you can add and `ORDER BY` clause to influence the results, so for example the following query: ``` SELECT ID, Column1, Column2 FROM T GROUP BY Column1 ORDER BY ID DESC; ``` Would ensure that you get the following result: ``` ID | Column1 | Column2 | ----|---------+----------| 2 | A | Y | ``` because of the `ORDER BY ID DESC`, however this is not true ([as demonstrated here](http://www.sqlfiddle.com/#!2/4b917/1)). The [MySQL documents](http://dev.mysql.com/doc/refman/5.0/en/group-by-extensions.html) state: > The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. So even though you have an order by this does not apply until after one row per group has been selected, and this one row is non-determistic. The SQL-Standard does allow columns in the select list not contained in the GROUP BY or an aggregate function, however these columns must be functionally dependant on a column in the GROUP BY. From the SQL-2003-Standard: > 15) If T is a grouped table, then let G be the set of grouping columns of T. In each contained > in , each column reference that references a column of T shall reference some column C that > is functionally dependent on G or shall be contained in an aggregated argument of a > whose aggregation query is QS. For example, ID in the sample table is the PRIMARY KEY, so we know it is unique in the table, so the following query conforms to the SQL standard and would run in MySQL and fail in many DBMS currently (At the time of writing Postgresql is the closest DBMS I know of to correctly implementing the standard - [Example here](http://sqlfiddle.com/#!12/4a6a4/1)): ``` SELECT ID, Column1, Column2 FROM T GROUP BY ID; ``` Since ID is unique for each row, there can only be one value of `Column1` for each ID, one value of `Column2` there is no ambiguity about what to return for each row.
Why Mysql's Group By and Oracle's Group by behaviours are different
[ "", "mysql", "sql", "oracle", "group-by", "aggregate-functions", "" ]
I have one DB table which contains Payment(Merchant,Transaction,TimeStamp).where for teach transaction we can have multiple merchants. Now i want to form a query where for transaction in (val1, val2, val3) , we will get the merchant who did latest transaction.eg: ``` Merchant Transaction Time ---------------------------------- M1 T1 t1 M2 T1 t2 M1 T1 t3 M3 T2 t4 M4 T2 t5 M5 T3 t6 ``` so in case where transactionid in (T1,T2.T3) , we will get M1 (since M1 did latest T1 transaction on time t3),M4,M5 `(t1<t2 timestamp)`
``` SELECT Merchant FROM DB_TABLE WHERE transaction IN(T1, T2, T3) ORDER BY Time DESC LIMIT 1 ```
``` select * from Payment group by transaction order by Time desc; ```
Regarding sql queryformation
[ "", "mysql", "sql", "" ]
I have a table called documents with a row called Nigel Harding ``` DOCUMENTS id | label 24 | Nigel Harding ``` He has been tagged with two other documents one with an ID of 1 & 12 that table is called document tags ``` DOCUMENT_TAGS id | label | Document_id 1 | TAG A | 24 12 | TAG B | 24 ``` I am trying to create a query where I can find one result where Nigel Harding will appear once if searching for the tags **1 AND 12** but i'm having no luck. I figured out the query for searching one tag id but i'm trying to do the query for both tags. ``` SELECT documents.id FROM documents LEFT JOIN documents_tags ON documents.id=documents_tags.document_id WHERE documents_tags.tag_id = 1 ORDER BY documents.label ``` I understand why adding... ``` AND documents_tags.tag_id = 12 ``` ...to the end of that will not work but i'm not sure what i need to do get the correct query display my one result as my understanding of SQL is very basic.
I think the most flexible way to approach this type of problem is to use aggregation with a `having` clause. Here is one example: ``` SELECT dt.document_id FROM documents_tags dt GROUP BY dt.document_id HAVING sum(dt.tag_id = 1) > 0 and sum(dt.tag_id = 12) > 0; ``` Each condition in the `having` clause counts the number of document tags that are 1 (or 12) and the filter passes only when both are found. You could also write this as: ``` SELECT dt.document_id FROM documents_tags dt WHERE dt.tag_id in (1, 12) GROUP BY dt.document_id HAVING count(distinct dt.tag_id) = 2; ```
If I understand your question, you're just lacking `IN` and `DISTINCT`: ``` SELECT DISTINCT documents.id FROM documents LEFT JOIN documents_tags ON documents.id=documents_tags.document_id WHERE documents_tags.tag_id IN (1, 12) ORDER BY documents.label ``` Using `IN` you'll be getting documents for any of the tag ids specified, and using `DISTINCT` you'll make sure to get each document id only once. --- **EDIT:** Since you're ordering by documents.label, I'm guessing that's what you want displayed. Don't forget you can change your `SELECT` statement to: ``` SELECT DISTINCT documents.label ``` or even to: ``` SELECT DISTINCT documents.id, documents.label ```
SQL Multiple Left joins
[ "", "mysql", "sql", "" ]
I have like 11 columns in my database table and i am inserting data in 10 of them. i want to have a unique number like "1101 and so on" in the 11th column. Any idea what should i do?? Thanks in advance.
SQL Server 2012 and above you can generate `Sequence` ``` Create SEQUENCE RandomSeq start with 1001 increment by 1 Go Insert into YourTable(Id,col1...) Select NEXT VALUE FOR RandomSeq,col1.... ``` or else you can use `Identity` ``` Identity(seed,increment) ``` You can start the seed from 1101 and increment the sequence by 1 ``` Create table YourTable ( id INT IDENTITY(1101,1), Col varchar(10) ) ```
If you want to have that unique number in a different field then you can manipulate that field with primary key and insert that value. If you want in primary key value, then open the table in design mode, go to 'Identity specification', set 'identity increment' and 'identity seed' as you want. Alternatively you can use table script like, ``` CREATE TABLE Persons ( ID int IDENTITY(12,1) PRIMARY KEY, FName varchar(255) NOT NULL, ) ``` here the primary key will start seeding from 12 and seed value will be 1.
SQL Server Database unique number generation on any record insertion
[ "", "sql", "sql-server", "database", "" ]
For example, I got a table: ``` Name , Area, Age cat , 1 , 10 dog , 2 , 7 cat , 3 , 11 horse , 4 , 4 cat , 5 , 10 dog , 6 , 9 ``` When I group by 'Name', for each group I want to retain the 'Area' of the MAX 'Age' in that group. In this example, I wanna get: ``` Name , Area cat , 3 dog , 6 horse, 4 ``` How should I do this in one query? Thanks guys!
Try something like this: ``` SELECT name, area FROM mytable JOIN ( SELECT name, MAX(age) as maxage FROM mytable GROUP BY name ) AS `max` ON mytable.name = max.name AND mytable.age = max.maxage ``` This first selects the `name` and `MAX(age)` in a subquery, and then joins them to the original table so that you can get the `area` associated with the `MAX(age)`. By using `join` ie `inner join`, we insure that any results in the original table that had nothing to match do not show. Notice that you can't do something like: ``` SELECT name, MAX(age), area FROM mytable ``` Because `area` would be randomly selected from all the `area` values in the group. It wouldn't know which `area` you want. You might think that it would get you the `area` in the same row as the `MAX(age)`, but it will not. It doesn't actually know that is what you want.
This would be more slightly more efficient than the subquery approach mentioned by @deroby and @DamienBlack: ``` SELECT t1.name, t1.area FROM myTable t1 LEFT JOIN myTable t2 ON t1.name = t2.name AND t2.Age > t1.Age WHERE t2.some_primary_key IS NULL ORDER BY t1.name ``` Note that this requires some column known to contain a value that is not NULL (such as a primary key). You can substitute, `t2.some_primary_key` with any other non-null, indexed column as needed. SQLFiddle based off @deroby's [here](http://sqlfiddle.com/#!2/b32156/2).
SQL Grouping: conditional select in each group
[ "", "mysql", "sql", "group-by", "grouping", "" ]
I must not be using the right Google foo to find the correct answer. I have a table that looks like the following: ID Parent  Status   Name 1              NULL     0              Root 2             1              0              Group 1 3             6              400         WINXP32 4              2              400         WIN7 5              2              400         WIN2K8 6              1              0              Group 2 The 'name' column contains both group names and machine names. Groups have a 'Status' of 0. How would I create a SQL statement to display (not modify the database) a column called 'Group' based on the logic that the 'Parent' column holds the 'ID' of its parent. Somehow I can figure out how to join data from other tables but I cant figure this out... -- Update: I forgot to show an example of the output I'm looking for, in a perfect world I would get the following.. ID | Group | Status | Name 3 | Group 2 | 400 | WINXP32 4 | Group 1 | 400 | WIN7 5 | Group 1 | 400 | WIN2K8 I would (i think) filter out the groups from the output by doing a where status > 0 Thanks everyone for the quick feedback !
Do you mean something like this (Self join in SQL standard)? If it's possible that you have records with missing Parent ID: ``` select t1.name, t2.name as "Group" from tab t1 left join tab t2 on t1.parent = t2.id where t1.status > 0; ``` If Parent ID is always present, you can use an inner join: ``` select t1.name, t2.name as "Group" from tab t1, tab t2 where t1.parent = t2.id and t1.status > 0; ``` Otherwise, please can you explain what you need?
Try like thsi ``` SELECT ID, CASE WHEN STATUS = 0 THEN (SELECT Root WHERE Parent = ID) END [Group] Status, Name FROM TABLE1 WHERE STATUS <> 0 ```
Creating a SQL column based on the value of another column in the same table
[ "", "sql", "" ]
IN this sql we are looking for subst\_instructions from the formulary table. we are getting only 1 or 2 of these, even though there should be others with same med in the first table: ``` select * from (SELECT ID_KEY, [BATCH] AS column1, [IMPORTDATE], [DATEBILLED], [RX], [DATEDISPENSED], [DAYSUPPLY], [PAYTYPE], [NPI], [PHYSICIAN], [COST], [QUANTITY], [MEDICATION], A.[NDC], [PATIENTNAME], [ROUTEOFADMIN], [INVOICECAT], [COPAY], [BRAND], [TIER], [SKILLLEVEL], [STAT] STATUS, [LASTTASKDATE],SEQNO,B.[SUBST_INSTRUCTIONS], row_number() over(partition by ID_KEY order by ID_KEY) rn FROM [PBM].[T_CHARGES] A LEFT OUTER JOIN [OGEN].[NDC_M_FORMULARY] B ON A.[NDC] = B.[NDC] Where [STAT] not in (3, 4) AND [TIER] <> 'T1' )a where rn = 1 ``` --- Here is the query that ended up working: ``` select * from (SELECT ID_KEY, [BATCH] AS column1, [IMPORTDATE], [DATEBILLED], [RX], /> [DATEDISPENSED], [DAYSUPPLY], [PAYTYPE], [NPI], [PHYSICIAN], [COST], [QUANTITY], [MEDICATION], A.[NDC], [PATIENTNAME], [ROUTEOFADMIN], <br> [INVOICECAT], [COPAY], [BRAND], [TIER], [SKILLLEVEL], <br> [STAT] STATUS, [LASTTASKDATE],SEQNO,B.[SUBST_INSTRUCTIONS],<br> row_number() over(partition by ID_KEY order by ID_KEY) rn FROM [PBM].[T_CHARGES] A<br> LEFT OUTER JOIN [OGEN].[NDC_M_FORMULARY] B ON A.[NDC] = B.[NDC] Where [STAT] not in <br> (3, 4) AND [TIER] <> 'T1' )a where SUBST_INSTRUCTIONS is not null -- rn = 1 ```
Sometimes Nulls can hide data you want. e.g. ``` CREATE TABLE #STAT ( ID INT IDENTITY(1,1), STAT INT NULL ) INSERT INTO #STAT (STAT) SELECT 3 UNION ALL SELECT NULL UNION ALL SELECT 4 UNION ALL SELECT 5 SELECT * FROM #STAT SELECT * FROM #STAT WHERE [STAT] NOT IN (3,4) ``` To get around this, use COALESCE ``` SELECT * FROM #STAT WHERE COALESCE([STAT],0) NOT IN (3,4) ```
The `where rn = 1` is going to be limiting, if you run the query without that, do the results look more like you expect?
this sql query not returning all data from joined table
[ "", "sql", "" ]
I need update a field with the same table. In the example below The RewRate is set correct in Co 1 , then I need updated the NewRate for Co 4, 10 and 16. based on the EDL Type, EDL Code. Thanks ![enter image description here](https://i.stack.imgur.com/aonaq.jpg) This code is obviously wrong, but i just do not know how to fix it. sorry ``` UPDATE PRCI SET NewRate = (select NewRate from PRCI where PRCI.PRCo=1 and Craft ='xxx') ``` Sorry for the confusing. I need update EDL Code300 NewRate 0.05, EDL Code700 NewRate 5.3 EDL Code701 NewRate 3.7 EDL Code707 NewRate 0.78 EDL Code714 NewRate 3 For company 4 10 and 16
There you go. ``` UPDATE t1 SET t1.NewRate=t2.NewRate FROM PRCI t1 INNER JOIN PRCI t2 ON t1.EDLType=t2.EDLType AND t1.EDLCode=t2.EDLCode WHERE t1.PRCo!='1'; ```
You can change ``` and Craft ='xxx' ``` to ``` and EDLCode = 714. ``` As mentioned in the comments, a where clause might be appropriate.
How to update a field in the same table
[ "", "sql", "sql-update", "" ]
I am using PHP, MySQL. I have two tables 1.categories ``` cat_id cat_name 1 cars 2 mobile 3 computers 4 radios ``` 2.posts ``` id title body cat_id 1 title1 txt1 cars 2 title2 txt2 mobiles 3 title3 txt3 mobiles 4 title4 txt4 radios ``` And I want to update the posts table replacing the cat\_id value with categories table and want the following output ``` id title body cat_id 1 title1 txt1 1 2 title2 txt2 2 3 title3 txt3 2 4 title4 txt4 4 ``` Is there Any SQL Statement That Can Do this in One Go?
Here is an SQL query that should do the trick: ``` UPDATE posts JOIN categories ON posts.cat_id = categories.cat_name SET posts.cat_id = categories.cat_id ```
Try ``` UPDATE post p JOIN categories c ON p.cat_id=c.cat_name SET p.cat_id=c.cat_id ```
How to Replace and Update Data From One Table to Another Table in MySQL
[ "", "mysql", "sql", "database", "" ]
I'm struggling with a query where there are some null values, and in my CASE statement, the test for the NULL values is not being processed. I've tried ordering the tests differently, but it doesn't seem to make a difference. ``` SELECT Title, library.LibraryID, Registered FROM libraries LEFT JOIN (SELECT LibraryID,UserID, (CASE >>> WHEN UserID IS NULL THEN "False" <<<<<<<< PROBLEM WHEN UserID=1 THEN "YES! Registered" ELSE "Not Registered" END) AS Registered FROM librariesandmembers WHERE UserID=1) AS myAlias ON libraries.LibraryID = myAlias.LibraryID'); ``` I've then tried a ``` WHEN USerID<>1 THEN "False" ``` But that doesn't change anything. This is a PHP/MySQL app. The results in phpmyAdmin shows that the results of my query are producing NULLS where I want "False" to appear. What am I missing? Must be something obvious but I just cannot see it. [EDIT] Let me try explain the objective this way: I want to have a list of all (e.g. 5) libraries with the result next to it that the user is "Yes! Registered" or "Not Registered". There may or may not be a corresponding entry in librariesandmembers table. hence the NULL problem.
This is your query: ``` SELECT Title, l.LibraryID, Registered FROM libraries lLEFT JOIN (SELECT LibraryID, UserID, (CASE WHEN UserID IS NULL THEN "False" <<<<<<<< PROBLEM WHEN UserID=1 THEN "YES! Registered" ELSE "Not Registered" END) AS Registered FROM librariesandmembers WHERE UserID = 1 ) AS myAlias ON l.LibraryID = myAlias.LibraryID; ``` Within the subquery, `userId` always has the value of `1`, so the `case` statement only says `'YES! Registered'`. You want to move that to the outer level. To get the same effect, the condition `UserId=1` has to move to the `on` clause: ``` SELECT Title, l.LibraryID, Registered, (CASE WHEN myalias.UserID IS NULL THEN 'False' WHEN myalias.UserID = 1 THEN 'YES! Registered' ELSE 'Not Registered' END) AS Registered FROM libraries l LEFT JOIN librariesandmembers myalias ON l.LibraryID = myAlias.LibraryID and myalias.UserID = 1; ```
I'm almost certain this is to do with your join rather than your case statement. That is, you build your subquery result set with the switch to handle NULLs, then LOJ that to libraries, effectively creating wholly NULL records where no match exists. Thus your efforts with the Registered column are for naught. Try re-structuring your query like so: ``` SELECT Title, libraries.LibraryID, ( CASE WHEN librariesandmembers.UserID IS NOT NULL THEN "YES! Registered" ELSE "Not Registered" END ) as Registered FROM libraries LEFT JOIN librariesandmembers ON libraries.LibraryID = librariesandmembers.LibraryID AND librariesandmembers.UserID = 1 ``` Also, you are handling the UserID=1 criterion twice. Your subquery effectively removes all other UserID's and therefore you have no need of the ELSE clause (which handles when the UserID is neither 1 or NULL). I think you could move my suggested WHERE clause to be a second JOIN condition, but I think this would get you the same results. Perhaps someone can argue for/against my approach?
Are MySQL CASE statements prioritized?
[ "", "mysql", "sql", "" ]