Counting Items/Rows in DB as Columns Grouped by Another Column - sql

What I want to do is basically:
select Type, (Count(*) where Date='')as 10/1, (Count(*) where Date='')as 10/2
from my table
group by Type
What I want it to look like is:
Type 10/1 10/2
1 5 7
2 3 1
3 6 9
4 1 3
5 9 8
However, when I try to run a full select within each count column, I end up getting
Type 10/1 10/2
1 12 15
2 12 15
3 12 15
4 12 15
5 12 15
Any suggestions are appreciated. I'm not sure if I will need to run a pivot or not, but I wouldn't think so. Additionally after I can run that for any specific day, I was thinking about trying to put the date into a variable and trying to run the whole thing for a date range, generating columns dynamically for each day its run. I would probably create a new question for that though.

Try this;
SELECT TYPE
,SUM(CASE WHEN MyDate = '' THEN 1 ELSE 0 END) AS [10/1]
,SUM(CASE WHEN MyDate = '' THEN 1 ELSE 0 END) AS [10/2]
FROM MyTable
GROUP BY TYPE

Related

SQL How to SUM rows in second column if first column contain

View of a table
ID
kWh
1
3
1
10
1
8
1
11
2
12
2
4
2
7
2
8
3
3
3
4
3
5
I want to recive
ID
kWh
1
32
2
31
3
12
The table itself is more complex and larger. But the point is this. How can this be done? And I can't know in advance the ID numbers of the first column.
SELECT T.ID,SUM(T.KWH)SUM_KWH
FROM YOUR_TABLE T
GROUP BY T.ID
Do you need this one?
Let's assume your database name is 'testdb' and table name is 'table1'.
SELECT * FROM testdb.table1;
SELECT id, SUM(kwh) AS "kwh2"
FROM stack.table1
WHERE id = 1
keep running the query will all (ids). you will get output.
By following this query you will get desired output.
Hope this helps.

Fetching data from DB and populate a partitioned List

I am confused about this both from front end point of view as well as querying the data from SQLite Database. If you have any idea how to solve either of these please do answer.
SQLite Database
I have a table likes this:
transactionId | productId | quantity
1 2 1
2 4 0
3 1 null
4 3 1
5 9 1
6 6 0
7 1 1
8 7 1
9 8 1
10 2 1
11 0 null
12 3 1
13 5 1
14 7 1
15 1 0
16 2 1
17 9 1
18 0 null
19 2 1
Now I want to display this data in groups of 5 units(i.e. groups till 5 units are completed) in list in my flutter app.
So 1st group will have 8 items,
2nd will have 6 items,
and 3rd group will have 5 items
(and is still incomplete since more items can be added till quantity for that group becomes 5)
Something like this:
Now my App can have multiple groups like this. Also, I don't think Grid view builder can work here since for each group I'll have to display some data for the group as well as accumulated data (which isn't shown in the picture)
Questions:
1) How to query data from SQFLite database?
2) How to display the queried data in my Flutter App front end?
Unfortunately, this type of problem requires a recursive CTE (or other iterative processing).
Assuming that transactionId is consecutive with no gaps:
with recursive cte as (
select transactionId, productId,
coalesce(quantity, 0) as quantity,
1 as bin
from t
where transactionId = 1
union all
select t.transactionId, t.productId,
(case when cte.quantity > 5
then 0 else cte.quantity
end) + coalesce(t.quantity, 0) as quantity,
(case when cte.quantity > 5 then 1 else 0 end) + cte.bin as bin
from cte join
t
on t.transactionId = cte.transactionId + 1
)
select *
from cte;
If transactionId has gaps or other issues, just use row_number() (in another CTE) to create an appropriate column for the where clauses.

Working out the percentage of outcomes in a column within a table

I am using SQL developer and have a table called table1 which looks like this (but with loads more data):
item_id seller_id warranty postage_class
------- --------- -------- -------------
14 2 1 2
17 6 1 1
14 2 1 1
14 2 1 2
14 2 1 1
14 2 1 2
I want to identify the percentage of items sent by first class.
If anyone could help me out that would be amazing!
You can use conditional aggregation. The simplest method is probably:
select avg(case when postage_class = 1 then 1.0 else 0 end)
from t;
Note this calculates a ratio between 0 and 1. If you want a "percentage" between 0 and 100, then use 100.0 instead of 1.0.
Some databases make it possible to shorten this even further. For instance, in Postgres, you can do:
select avg( (postage_class = 1)::int )
from t;

SQL - Creating a Grouped 'range' set

I have a table of support tickets - with time opened and time closed. I would like to create a table of ranges, as such:
ticket count | time to close
----------------------------------
30 | up to 2 hours
25 | 2 - 4 hours
10 | 4 - 6 hours
what i have so far gives me the range (using a CASE with DATEDIFF), but i cant figure out how to group the eventual range.
When trying to GROUP on the new openTimeRange computed column, the error of course is that its an unknown column.
SELECT COUNT([tblTickets].*), DATEDIFF(hh,[dateOpened],[closeDate]) AS OpenTime
, case when DATEDIFF(hh,[dateOpened],[closeDate]) between 0 and 2 then '0-2'
when DATEDIFF(hh,[dateOpened],[closeDate]) between 3 and 4 then '3-4'
when DATEDIFF(hh,[dateOpened],[closeDate]) between 5 and 6 then '4-6'
end as openTimeRange
FROM [tblTickets]
WHERE closeDate is not null
GROUP BY [dateOpened],[closeDate]
Using MSSQL 2005 SP4
Thanks!
As you mentioned, if you try to GROUP BY the openTimeRange alias column in your original query, you will get an error. The reason for this is that the GROUP BY clause is evaluated before the alias is assigned to the result set, and hence you cannot use it. Using an inline view should do the trick:
SELECT T.TicketCount, T.OpenTime, T.openTimeRange
FROM
(
SELECT COUNT([tblTickets].*) AS TicketCount,
DATEDIFF(hh,[dateOpened],[closeDate]) AS OpenTime,
CASE WHEN DATEDIFF(hh,[dateOpened],[closeDate]) BETWEEN 0 AND 2 THEN '0-2'
WHEN DATEDIFF(hh,[dateOpened],[closeDate]) BETWEEN 3 AND 4 THEN '3-4'
WHEN DATEDIFF(hh,[dateOpened],[closeDate]) BETWEEN 5 AND 6 THEN '4-6'
END AS openTimeRange
FROM [tblTickets]
WHERE closeDate IS NOT NULL
GROUP BY [dateOpened],[closeDate]
) T
GROUP BY T.openTimeRange

Inserting a new indicator column to tell if a given row maximizes another column in SQL

I currently have a table in SQL that looks like this
PRODUCT_ID_1 PRODUCT_ID_2 SCORE
1 2 10
1 3 100
1 10 3000
2 10 10
3 35 100
3 2 1001
That is, PRODUCT_ID_1,PRODUCT_ID_2 is a primary key for this table.
What I would like to do is use this table to add in a row to tell whether or not the current row is the one that maximizes SCORE for a value of PRODUCT_ID_1.
In other words, what I would like to get is the following table:
PRODUCT_ID_1 PRODUCT_ID_2 SCORE IS_MAX_SCORE_FOR_ID_1
1 2 10 0
1 3 100 0
1 10 3000 1
2 10 10 1
3 35 100 0
3 2 1001 1
I am wondering how I can compute the IS_MAX_SCORE_FOR_ID_1 column and insert it into the table without having to create a new table.
You can try like this...
Select PRODUCT_ID_1, PRODUCT_ID_2 ,SCORE,
(Case when b.Score=
(Select Max(a.Score) from TableName a where a.PRODUCT_ID_1=b. PRODUCT_ID_1)
then 1 else 0 End) as IS_MAX_SCORE_FOR_ID_1
from TableName b
You can use a window function for this:
select product_id_1,
product_id_2,
score,
case
when score = max(score) over (partition by product_id_1) then 1
else 0
end as is_max_score_for_id_1
from the_table
order by product_id_1;
(The above is ANSI SQL and should run on any modern DBMS)