Simple SQL Statement query using IIF - sql

I am trying to report a simple 3 column query using MS Query from a single Table, The 3 columns are 'Sales Person [EXECNAME]', 'No of Cars Sold [ITEM]', 'No of Cars That had Finance on it' [FINANCECASES]. There is no field which simply shows YES for Finance, but the is a field with the Finance Value, so I was trying to use the IIF to simply add 1 for each record that had a FinanceValue that doesn't = 0. Here is my attempt but it is simply not working? Any help would be much appreciated.
SELECT t.EXECNAME, COUNT(t.ITEM),
IIF(SUM(t.TOTALFINANCE) = 0, 0, SUM(FINANCECASES) + 1) AS FINANCECASES
FROM t.csv t
GROUP BY t.EXECNAME
Steve

SELECT t.EXECNAME, COUNT(t.ITEM),
SUM(CASE WHEN t.TOTALFINANCE > 0 THEN 1 ELSE 0 END) AS FINANCECASES
FROM t.csv t
GROUP BY t.EXECNAME

Related

SQL SSMS 2017 Detailed result

I´m a bit newbie to SQL, so I want to ask for possible solution how to create a query which will show the desired results.
There´s a table where are the data coming continuously from one main PLC so everything is gathered in 1 table. There are a bunch of data per 1 shift (about half million). In column "Op" are the machines represented by their IDs (Op = ID of machine). Machines are about from 1 to 218. Every machine has it´s their cycle times divided into starting process (T1), duration (T2), end process(T3) and Result. The "Result" can be interpreted as 0 - as OK, 1 - not OK, 2 - empty pallet, 3 - free flow of pallet. Those are the Results of what the PLCs are reporting directly into database´s table.
I have tried the basic statements to count these results for exact record states (0,1,2,3) and for exact machine. That´s OK but not the desired goal.
SELECT Count(*) as Result0
FROM PalletOperations
where Op = 1 and Result = 0
The expected result is to show a full list of every machines from 1 to 218 how many results were counted as 0, 1, 2 and 3. The other columns are not relevant for this time. The main goal is to show a result as every machine has its own row with the expected data of counted states result. If theres 218 machines, than I need to generate results of 218 machines separately from 1 to 218 in rows. Each row should contain the Op(name 1,2,3,4....218) with the columns of counted result for states 0,1,2,3 as mentioned above.
Any advice is welcome
I think you want conditional aggregation:
SELECT op,
SUM(CASE WHEN Result = 0 THEN 1 ELSE 0 END) as result_0,
SUM(CASE WHEN Result = 1 THEN 1 ELSE 0 END) as result_1,
SUM(CASE WHEN Result = 2 THEN 1 ELSE 0 END) as result_2,
SUM(CASE WHEN Result = 3 THEN 1 ELSE 0 END) as result_3
FROM PalletOperations
GROUP BY op;
you can use the below sql statement to get count of results per machine per result
SELECT op,Result, count(*)
FROM PalletOperations
GROUP BY op,Result;

Qualifying a column in a SQL select statement

I'm looking to generate a query that pulls from several tables. Most are rather straightforward and I can pull a value from a table directly but there is one table that is pivoted so that the value I want depends on the value in another column.
The table looks like the below:
ID Condition Value
1 Stage1 6
2 Stage2 9
3 Stage3 5
4 Stage4 2
So I'm looking to write a query that essentially "qualifies" the value I want by telling the table which condition.
An example of my SQL:
Select Attribute1, Stage1Value, Stage2Value, Stage3Value
From attribute, stage
where attribute = project1
So I can't just pull the "Value" column as it needs to know which stage in the query.
There are 30 columns I am trying to pull - of which 13 fall into this category. Thanks for any help you can provide.
So, you want conditional aggregation something :
select a.<col>,
sum(case when s.Condition = 'Stage1' then s.value else 0 end),
. . .
sum(case when s.Condition = 'Stage4' then s.value else 0 end)
from attribute a inner join
stage s
on s.<col> = a.<col>
group by a.<col>

select sum(a), sum(b where c=1) from db; sql conditions in select statement

i guess i just lack the keywords to search, but this is burning on my mind:
how can i add a condition to the sum-function in the select-statement like
select sum(a), sum(b where c=1) from db;?
this means, i want to see the sum of column a and the sum of column b, but only of the records in column b of which column c has the value 1.
the output of heidi just says "bad syntac near WHERE". may there be any other way?
thanks in advance and best regards from Berlin, joachim
The exact syntax may differ depending on the database engine, however it will be along the lines of
SELECT
sum(a),
sum(CASE WHEN c = 1 THEN b ELSE 0 END)
FROM
db
select sum(case when c=1 then b else 0 end)
This technique is useful when you need a lot of aggregates on the same set of data - you can query the entire table without applying a where filter, and have a bunch of these which give you aggregated data for a specific filter.
It's also useful when you need a lot of counts based on filters - you can do sums of 1 or 0:
select sum(case when {somecondition} then 1 else 0 end)

SQL-Server - Ability to pass subset parameter in the select?

I'm trying create a query that will output a total number, as well as a subset of the total number in SQL-Server. I can think of a way to do this via subqueries, but that seems like a ton of work. Is there a faster way to write this query?
Table name: orders
OrderID Date Type OrderSize
1 1/1/2012 Electronics $282.02
2 1/1/2012 Electronics $1,000.56
3 1/1/2012 Books $17.25
4 1/1/2012 Books $10.00
What I am trying to output would look like this:
Date ElectronicOrders ElectronicOrderSize BookOrders BookOrderSize
1/1/2012 2 $1,282.58 2 $27.25
I could create a temp table, then run 2 update queries - 1 WHERE Type = 'Electronics' and 1 WHERE Type = 'Books'.
What I have seen in some programming languages, such as R, is the ability to subset a variable. Is there a way for me to say something like:
count(OrderID, Type = 'Electronics) as ElectronicOrders, sum(OrderSize, Type = 'Electronics') as ElectronicOrderSize
Or am I stuck with subqueries and UPDATE queries?
I haven't ever gotten the new PIVOT syntax to make sense in my head but you can do a pivot table by grouping, and taking aggregate functions in a case statement.
select [date], sum( case when type = 'Electronics' then (ordersize) else 0 end) AS ElectronicsSum,
sum( case when type = 'Electronics' then 1 else 0 end) AS ElectronicsCount,
sum( case when type = 'Books' then (ordersize) else 0 end) AS BooksSum,
sum( case when type = 'Books' then 1 else 0 end) AS BooksCoumt
from orders
group by [date]
I put a fiddle thing up to test it out. If Aaron B. posts up a solution, give him the answer credit, I might not have even recognized the pivotyness of it.

SQL multiple COUNT

Let's consider this table:
[name] [type]
"Ken Anderson" 1
"John Smith" 2
"Bill Anderson" 1
"George Anderson" 1
"Taylor Smith" 1
"Andrew Anderson" 2
"Dominic Smith" 2
and that query:
SELECT mates.type, COUNT(*) AS SmithsCount
FROM mates
WHERE mates.name LIKE "* Smith"
GROUP BY mates.type
The result should be like
[type] [SmithsCount]
1 1
2 2
What if I want to get also Andersons Count in each group? Like
[type] [SmithsCount] [AndersonsCount]
1 1 3
2 2 1
And, of course, I want this to be most simple as it can be ;) I'm pretty new in SQL, I readed tutorials on W3 Schools and http://www.sql-tutorial.net/ but there are just poorly exampled basics, any "more" complicated queries. Anybody has some useful links? Thanks.
select type,
sum(case when name like '% Smith' then 1 else 0 end) as SmithCount,
sum(case when name like '% Anderson' then 1 else 0 end) as AndersonCount
from mates
group by type
You need a pivot table. This is a feature supported by some RDBMS (Oracle, SQLServer and probably others).
A pivot table let's you use values as columns for aggregations. See my post here: How to transform vertical data into horizontal data with SQL?
The pivot table will alow you to also get the counts of all the other people in your list.
Your query is close, but you must use % instead of * as the wildcard character.
select type,
sum(case when name like '%Smith' then 1 else 0 end) as SmithCount,
sum(case when name like '%Anderson' then 1 else 0 end) as AndersonCount
group by type
In standard SQL parlance this is not supported in the presentation that you propose.
Standard SQL way would be to first normalize data into mates.first_name, mates.last_name and then do:
SELECT mates.type, mates.last_name, COUNT(*) AS last_name_count
FROM mates
WHERE mates.last_name IN ('Smith', 'Anderson')
GROUP BY mates.type, mates.last_name
Which would provide output such as
type last_name last_name_count
1 Anderson 3
1 Smith 1
2 Anderson 1
2 Smith 2
this is the same info that you are looking for, but the format/presentation is not the same.
Historically you were supposed to pivot/crosstab this data in the client application (as part of the presentation layer).
Of course a lot of times it is useful or necessary to do it in SQL layer so extensions to the standard were made, such as pivot (MSSQL) or crosstab (postgres), etc...