SQL: Count() based on column value

You can use a CASE expression with your aggregate to get a total based on the outcomeId value: select companyId, sum(case when outcomeid = 36 then 1 else 0 end) SalesCount, sum(case when outcomeid <> 36 then 1 else 0 end) NonSalesCount from yourtable group by companyId; See SQL Fiddle with Demo

Generate script for both schema and data

Backing up/Exporting database There are two ways to Back up/Export a SQL Server database using SQL Server Management Studio: Right click database → Tasks → Generate Scripts → Choose DB → Change “Script Data” option to true → … Right click database → Tasks → Backup → … The first method creates a .sql file … Read more

How to set table name in dynamic SQL query?

To help guard against SQL injection, I normally try to use functions wherever possible. In this case, you could do: … SET @TableName=”<[db].><[schema].>tblEmployees” SET @TableID = OBJECT_ID(TableName) –won’t resolve if malformed/injected. … SET @SQLQuery = ‘SELECT * FROM ‘ + QUOTENAME(OBJECT_NAME(@TableID)) + ‘ WHERE EmployeeID = @EmpID’

‘NOT LIKE’ in an SQL query

You have missed out the field name id in the second NOT LIKE. Try: SELECT * FROM transactions WHERE id NOT LIKE ‘1%’ AND id NOT LIKE ‘2%’ The AND in the where clause joins 2 full condition expressions such as id NOT LIKE ‘1%’ and can’t be used to list multiple values that the … Read more

Designing a SQL schema for a combination of many-to-many relationship (variations of products)

Applying normalization to your problem, the solution is as given. Run and see it on SQL Fiddle. CREATE TABLE products ( product_id int AUTO_INCREMENT PRIMARY KEY, name varchar(20), description varchar(30) ); INSERT INTO products (name, description) VALUES (‘Rug’, ‘A cool rug’ ), (‘Cup’, ‘A coffee cup’); — ======================================== CREATE TABLE variants ( variant_id int AUTO_INCREMENT … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)