Master-Detail show data SQL - asp.net

I'm working with SQL Server and I have this 3 tables
STUDENTS
| id | student |
-------------
| 1 | Ronald |
| 2 | Jenny |
SCORES
| id | score | period | student |
| 1 | 8 | 1 | 1 |
| 2 | 9 | 2 | 1 |
PERIODS
| id | period |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
And I want a query that returns this result:
| student | score1 | score2 | score3 | score4 |
| Ronald | 8 | 9 | null | null |
| Jenny | null | null | null | null |
As you can see, the number of scores depends of the periods because sometimes it can be 4 o 3 periods.
I don't know if I have the wrong idea or should I make this in the application, but I want some help.

You need to PIVOT your data e.g.
select Y.Student, [1], [2], [3], [4]
from (
select T.Student, P.[Period], S.Score
from Students T
cross join [Periods] P
left join Scores S on S.[Period] = P.id and S.Student = T.id
) X
pivot
(
sum(Score)
for [Period] in ([1],[2],[3],[4])
) Y
Reference: https://learn.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-20

Related

SQL LEFT JOIN not pulling intended data

I have the below tables:
CATEGORIES:
id | name | category_group | cate_type_id
1 | Entertainment | Entertainment | 1
2 | Electricity | Utilities | 8
3 | Water | Utilities | 8
4 | Rent | Living Exp | 6
5 | credit card | Finance | 5
BUDGET-ITEMS:
id | budget_id | cat_id | category_group| budget_yr | budget_01 | budget_02 | ... | budget_12
1 | 1 | 1 | Entertainment | 2022 | 500 | |
2 | 1 | 2 | Utilities | 2022 | 1500 | |
3 | 1 | 3 | Utilities | 2022 | | 250 |
I want to pull all items from Category table with mapping budget columns. Below is my JOIN.
SELECT c.id as base_id,c.name,c.category_type_id, c.category_group as base_group, b.*
FROM category c
LEFT JOIN budget_items b ON c.id = b.category_id
WHERE c.category_type_id NOT IN (5)
ORDER BY c.category_type_id, c.category_group ASC
I expect the below output:
id | budget_id | cat_id | catgroup | budget_yr | budget_01 | budget_02 | ... | budget_12
1 | 1 | 1 | Entertainment | 2022 | 500 | |
2 | 1 | 2 | Utilities | 2022 | 1500 | |
3 | 1 | 3 | Utilities | 2022 | | 250 |
4 | 1 | 4 | Living Exp | 2022 | | |
However, I get like below (truncated base* columns here for space):
id | budget_id | cat_id | catgroup | budget_yr | budget_01 | budget_02 | ... | budget_12
1 | 1 | 1 | Entertainment | 2022 | 500 | |
2 | 1 | 2 | Utilities | 2022 | | 1500 |
3 | 1 | 3 | Utilities | 2022 | | |
4 | 1 | 4 | Living Exp | 2022 | | |
My query looks OK, not sure where it is going wrong. Does anyone see the issue?
Thanks in advance for your kind help.
Edit:
I have truncated some columns for space here. the problem is the values are aligned to different budget columns. I get the columns correctly from the left table.
Edit:
Thanks to everyone who pitched in to help, I finally figured the issue was with my data. The query was actually working fine. This community is amazing.
Not sure what you're doing, but it seems to work as expected for me:
Schema (SQLite v3.30)
CREATE TABLE items (
`id` INTEGER,
`budget_id` INTEGER,
`cat_id` INTEGER,
`catgroup` VARCHAR(13),
`budget_yr` INTEGER,
`budget_01` INTEGER,
`budget_02` INTEGER
);
INSERT INTO items
(`id`, `budget_id`, `cat_id`, `catgroup`, `budget_yr`, `budget_01`, `budget_02`)
VALUES
('1', '1', '1', 'Entertainment', '2022', '500', null),
('2', '1', '2', 'Utilities', '2022', '1500', null),
('3', '1', '3', 'Utilities', '2022', null, '250');
CREATE TABLE cats (
`id` INTEGER,
`name` VARCHAR(13),
`category_group` VARCHAR(13),
`cate_type_id` INTEGER
);
INSERT INTO cats
(`id`, `name`, `category_group`, `cate_type_id`)
VALUES
('1', 'Entertainment', 'Entertainment', '1'),
('2', 'Electricity', 'Utilities', '8'),
('3', 'Water', 'Utilities', '8'),
('4', 'Rent', 'Living Exp', '6'),
('5', 'credit card', 'Finance', '5');
Query
SELECT c.id
, budget_id
, cat_id
, catgroup
, budget_yr
, budget_01
, budget_02
FROM cats c
LEFT JOIN items i ON c.id = i.cat_id
WHERE c.cate_type_id <> 5;
id
budget_id
cat_id
catgroup
budget_yr
budget_01
budget_02
1
1
1
Entertainment
2022
500
2
1
2
Utilities
2022
1500
3
1
3
Utilities
2022
250
4
View on DB Fiddle

How do you assign groups to larger groups dpylr

I would like to assign groups to larger groups in order to assign them to cores for processing. I have 16 cores.This is what I have so far
test<-data_extract%>%group_by(group_id)%>%sample_n(16,replace = TRUE)
This takes staples OF 16 from each group.
This is an example of what I would like the final product to look like (with two clusters),all I really want is for the same group id to belong to the same cluster as a set number of clusters
________________________________
balance | group_id | cluster|
454452 | a | 1 |
5450441 | a | 1 |
5444531 | b | 1 |
5404051 | b | 1 |
5404501 | b | 1 |
5404041 | b | 1 |
544251 | b | 1 |
254252 | b | 1 |
541254 | c | 2 |
54123254 | d | 1 |
542541 | d | 1 |
5442341 | e | 2 |
541 | f | 1 |
________________________________
test<-data%>%group_by(group_id)%>% mutate(group = sample(1:16,1))

How can I execute multiple queries in one query?

I am building a chat application where I am using Firebase to send and receive messages. Once I send or receive a message, I am storing it to SQLite as follows. Now it the recent chats screen, I need the last message from all the unique chats, number of unread messages in those unique chats in one single query as I am observing the SQLite database.
Mid(STRING) | SentBy | SentTo | message | readTime | sentTime| Type
----------------+--------+--------+---------+----------+---------+------
A | AA | JD | M1 | 1 | 0 | S
B | JD | AA | M2 | 2 | 1 | s
C | AA | JD | M3 | 3 | 2 | s
D | AB | JD | m5 | null | 3 | s
E | AA | JC | M1 | 5 | 4 | s
F | JD | AB | M2 | 6 | 5 | s
G | AA | JD | M3 | 7 | 6 | s
H | AA | JC | m5 | 8 | 7 | s
I | AA | JD | M1 | null | 8 | s
J | JD | AA | M2 | 10 | 9 | s
K | AA | JD | M3 | 11 | 10 | s
L | AB | JC | m5 | 12 | 11 | s
M | AA | JD | M1 | 13 | 12 | s
N | JC | AA | M2 | 14 | 13 | s
O | AB | JD | M3 | 15 | 14 | s
P | JC | JD | m5 | 16 | 15 | s
I tried
SELECT *,COUNT() FROM messagesTable GROUP BY min ( sentBy, sentTo ), max( sentBy , sentTo ) ORDER BY sentTime desc
This query gives me the last messages from every combination of sentTo and sentBy. But I also need to know how many messages are unread for that combination. I want to run a query for every row like
SELECT COUNT() FROM messagesTable WHERE sentBy = message.sentBy, sentTo = message.sentTo, readTime = null
How can I run both queries in a single query?
You must group by the combination of (sentby, sentto) and with a straight count(*) get the total number of messages and with conditional aggregation you can get the number of unread mesages.
Then join to the result to the table to get also the last message:
select
g.user1, g.user2, g.lasttime, m.message lastmessage,
g.totalcounter, g.unreadcounter
from messagestable m inner join (
select
min(sentby, sentto) user1, max(sentby, sentto) user2,
max(senttime) lasttime, count(*) totalcounter,
sum(case when readtime is null then 1 else 0 end) unreadcounter
from messagestable
group by user1, user2
) g
on g.user1 = min(m.sentby, m.sentto) and g.user2 = max(m.sentby, m.sentto)
and g.lasttime = m.senttime
order by g.lasttime desc
See the demo.
Results:
| user1 | user2 | lasttime | lastmessage | totalcounter | unreadcounter |
| ----- | ----- | -------- | ----------- | ------------ | ------------- |
| JC | JD | 15 | m5 | 1 | 0 |
| AB | JD | 14 | M3 | 3 | 1 |
| AA | JC | 13 | M2 | 3 | 0 |
| AA | JD | 12 | M1 | 8 | 1 |
| AB | JC | 11 | m5 | 1 | 0 |

How to select sqlite columns based on a row lookup

I'm trying to compose an SQLite query and I've found a problem that's beyond my skillset. I'm trying to output columns that are based on the rows of another referenced table.
Food_List:
| food_id | name |
|---------|-----------|
| 1 | Apple |
| 2 | Orange |
| 3 | Pear |
Nutrient_Definition:
| nutrient_id | name |
|-------------|-----------|
| 21 | Carbs |
| 22 | Protein |
| 23 | Fat |
Nutrient_Data:
| food_id | nutrient_id | value |
|---------|-------------|-------|
| 1 | 21 | 50 |
| 1 | 22 | 24 |
| 1 | 23 | 63 |
| 2 | 22 | 12 |
| 2 | 23 | 95 |
| 3 | 21 | 66 |
| 3 | 22 | 87 |
| 3 | 23 | 38 |
Output:
| food_id | name | Carbs | Protein | Fat |
|---------|-----------|-------|---------|-----|
| 1 | Apple | 50 | 24 | 63 |
| 2 | Orange | | 12 | 95 |
| 3 | Pear | 66 | 87 | 38 |
(Note that Orange does not have a "Carbs" entry in the Nutrient_Data table)
I believe the following will do what you want :-
DROP TABLE IF EXISTS food_list;
CREATE TABLE IF NOT EXISTS food_list(food_id INTEGER PRIMARY KEY, name TEXT);
DROP TABLE IF EXISTS nutrient_definition;
CREATE TABLE IF NOT EXISTS nutrient_definition(nutrient_id INTEGER PRIMARY KEY, name TEXT);
DROP TABLE IF EXISTS nutrient_data;
CREATE TABLE IF NOT EXISTS nutrient_data(food_id INTEGER, nutrient_id INTEGER, value INTEGER);
INSERT INTO food_list (name) VALUES
('apple'),('orange'),('pear')
;
INSERT INTO nutrient_definition (name) VALUES
('carbs'),('protien'),('fat')
;
INSERT INTO nutrient_data VALUES
(1,1,50),(1,2,24),(1,3,63),
(2,2,12),(2,3,95),
(3,1,66),(3,2,87),(3,3,38)
;
SELECT food_list.food_id,food_list.name,
(
SELECT value
FROM nutrient_data
WHERE nutrient_data.food_id = food_list.food_id AND
nutrient_data.nutrient_id = (SELECT nutrient_definition.nutrient_id FROM nutrient_definition WHERE nutrient_definition.name = 'carbs')
),
(
SELECT value
FROM nutrient_data
WHERE nutrient_data.food_id = food_list.food_id AND
nutrient_data.nutrient_id = (SELECT nutrient_definition.nutrient_id FROM nutrient_definition WHERE nutrient_definition.name = 'protien')
),
(
SELECT value
FROM nutrient_data
WHERE nutrient_data.food_id = food_list.food_id AND
nutrient_data.nutrient_id = (SELECT nutrient_definition.nutrient_id FROM nutrient_definition WHERE nutrient_definition.name = 'fat')
)
FROM food_list
;
Results in :-

How do I analyze Market Basket Output?

I have a sale data as below:
+------------+------+-------+
| Receipt ID | Item | Value |
+------------+------+-------+
| 1 | a | 2 |
| 1 | b | 3 |
| 1 | c | 2 |
| 1 | k | 4 |
| 2 | a | 2 |
| 2 | b | 5 |
| 2 | d | 6 |
| 2 | k | 7 |
| 3 | a | 8 |
| 3 | k | 1 |
| 3 | c | 2 |
| 3 | q | 3 |
| 4 | k | 4 |
| 4 | a | 5 |
| 5 | b | 6 |
| 5 | a | 7 |
| 6 | a | 8 |
| 6 | b | 3 |
| 6 | c | 4 |
+------------+------+-------+
Using APriori algorithm, I modified the Rules into different columns:
For eg, I got output as below, I trimmed support, confidence, Lift value.. I am only considering rules which mapped into different columns into Target Item, Item1, Items ({Item1,Item2} -> {Target Item})
Output is as below:
+-------------+-------+-------+
| Target Item | Item1 | Item2 |
+-------------+-------+-------+
| a | b | |
| a | b | c |
| a | k | |
+-------------+-------+-------+
I am looking to calculate the all the receipts having the rules combination and identify the Target item Sale value only in those receipts and also Combined sale value of Item 1 and Item 2 in the combination receipts:
Output should be something like below (I dont need receipt ID's from below)
+-------------+-------+-------+--------------+----------------------+------------------------------+
| Target Item | Item1 | Item2 | Receipt ID's | Value of Target Item | Remaining value(Item1+item2) |
+-------------+-------+-------+--------------+----------------------+------------------------------+
| a | b | | 1,2,5,6 | 2+2+7+8 | 3+5+6+3 |
| a | b | c | 1,6 | 2 | (3+3) + (2+4) |
| a | k | | 1,2,3,4 | 2+2+8+5 | 4+7+1+4 |
+-------------+-------+-------+--------------+----------------------+------------------------------+
To replicate the Apriori:
library(arules)
Data <- data.frame(
Receipt_ID = c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,5,5,6,6,6),
item = c('a','b','c','k','a','b','d','k','a','k','c','q','k', 'a','b','a','a', 'b', 'c'
)
,
value = c(2,3,2,4,2,5,6,7,8,1,2,3,4,5,6,7,8,3,4
)
)
write.table(Data,"item.csv",sep=',',row.names = F)
data_frame = read.transactions(
file = "item.csv",
format = "single",
sep = ",",
cols = c("Receipt_ID","item"),
rm.duplicates = T
)
rules_apriori <- apriori(data_frame)
rules_apriori
rules_tab <- as(rules_apriori, "data.frame")
rules_tab
out <- strsplit(as.character(rules_tab$rules),'=>')
rules_tab$rhs <- do.call(rbind, out)[,2]
rules_tab$lhs <- do.call(rbind, out)[,1]
rules_tab$rhs <- gsub("\\{", "", rules_tab$rhs)
rules_tab$rhs <- gsub("}", "", rules_tab$rhs)
rules_tab$lhs = gsub("}", "", rules_tab$lhs)
rules_tab$lhs = gsub("\\{", "", rules_tab$lhs)
rules_final <- data.frame (target_item = character(),item_combination = character() )
rules_final <- cbind(target_item = rules_tab$rhs,item_Combination = rules_tab$lhs)
rules_final

Resources