Why do my values show as NULL when pivoting table in MySQL - mysql

I'm using MySQL - Rows to Columns and this tutorial http://stratosprovatopoulos.com/web-development/mysql/pivot-a-table-in-mysql/#comment-6128 to help me pivot a table and it's working pretty well. Starting with this:
mediaID q_short_name start_time stop_time audio_link
ee CVV Number 208 210 j.mp3
ee Expiration Date 308 310 j.mp3
ff CVV Number 124 127 k.mp3
ff Expiration Date 166 169 k.mp3
The goal is this:
mediaID CVVNumStartT CVVNumStopT ExpDateStart_time ExpDateStop_time Aud
ee 208 210 308 310 k.mp3
ff 124 127 166 169 j.mp3
I got part of the way there with this code:
CREATE VIEW test__extension AS (
SELECT amr_text.*,
CASE WHEN q_short_name = 'CVV Number' THEN amr_text.start_time END AS
CVV_Start_Time,
CASE WHEN q_short_name = 'CVV Number' THEN amr_text.stop_time END AS
CVV_Stop_Time,
CASE WHEN q_short_name = 'Expiration Date' THEN amr_text.start_time END
AS Expiration_Start_Time,
CASE WHEN q_short_name = 'Expiration Date' THEN amr_text.stop_time END
AS Expiration_Stop_Time, FROM amr_text);
CREATE VIEW test_extension_pivot AS (SELECT mediaID,
SUM(CVV_Start_Time) AS CVV_Start_Time,
SUM(CVV_Stop_Time) AS CVV_Stop_Time,
SUM(Expiration_Start_Time) AS Expiration_Start_Time,
SUM(Expiration_Stop_Time) AS Expiration_Stop_Time,
FROM test_extension GROUP BY mediaID);
This creates columns exactly like the goal table. But now the values for everything except the mediaIDs are rendered as NULL. My questions are, why did they get replaced by NULL, and what can I use instead of SUM to render the values of Expiration and CVV Start and Stop Time as they are in the original table?

Related

Use a single trigger to insert into multiple tables based on a condition

I have a table named three_current. this tables is inserted with 3 new rows every 1 minutes from another application, so the tables keeps on increasing in rows. These three new rows always have their channel number to be 350, 351, and 352. I want a trigger to insert each of these three rows into three separate tables such that each tables contains data with the same channel number.
The three_current tables is as such:
three_current table
datetime
channel_number
Value
Status
01/06/2021 22:45:00
350
100
1
01/06/2021 22:45:00
351
120
1
01/06/2021 22:45:00
352
110
1
01/06/2021 22:46:00
350
95
1
01/06/2021 22:46:00
351
105
1
01/06/2021 22:46:00
352
150
1
01/06/2021 22:47:00
350
195
1
01/06/2021 22:47:00
351
205
1
01/06/2021 22:47:00
352
250
1
I also have three other tables name red_current, yellow_current, and blue_current. I am trying without success to create a trigger to update these three tables based on the channel_number of three_current table such that
red_current table will be
datetime
channel_number
Value
Status
01/06/2021 22:45:00
350
100
1
01/06/2021 22:46:00
350
95
1
01/06/2021 22:47:00
350
195
1
yellow_current table will be
datetime
channel_number
Value
Status
01/06/2021 22:45:00
351
120
1
01/06/2021 22:46:00
351
105
1
01/06/2021 22:47:00
351
205
1
blue_current table will be
datetime
channel_number
Value
Status
01/06/2021 22:45:00
352
110
1
01/06/2021 22:46:00
352
150
1
01/06/2021 22:47:00
352
250
1
But what I get after executing my code is that the red_current, yellow_current and the blue_current tables are all being inserted with rows where the channel number is 350. This means that only the red_current table is correct while the other two tables are duplicates of the red_current table. (I feel my code can only execute for the first row of each updates received by three_current table and thats the row with channel number 350).
My code is as follows:
DELIMITER //
CREATE TRIGGER `add` AFTER INSERT ON `three_current`
FOR EACH ROW
BEGIN
DECLARE new_datetime datetime ; -- choose the datatypes
DECLARE new_channel_number int; --
DECLARE new_value double; --
DECLARE new_status smallint; --
SET new_datetime = new.datetime ;
SET new_channel_number = new.channel_number ;
SET new_value = new.value ;
SET new_status = new.status;
INSERT INTO red_current (datetime, channel_number, value, status)
SELECT new.datetime, new.channel_number , new.value, new.status
FROM three_current WHERE channel_number = '350'
ON DUPLICATE KEY UPDATE status = new.status;
INSERT INTO yellow_current (datetime, channel_number, value, status)
SELECT new.datetime, new.channel_number , new.value, new.status
FROM three_current WHERE channel_number = '351'
ON DUPLICATE KEY UPDATE status = new.status;
INSERT INTO blue_current (datetime, channel_number, value, status)
SELECT new.datetime, new.channel_number , new.value, new.status
FROM three_current WHERE channel_number = '352'
ON DUPLICATE KEY UPDATE status = new.status ;
END
//
DELIMITER ;

Apply a function for all columns of a table

I am trying to make a calculation in MySQL for all columns of a table.
Table: bev
Jahr GKZ gesamt A B C
2017 1111000 88.519 855 888 814
2017 1112000 247.943 2.414 2.379 2.262
2017 1113000 253.106 2.290 2.343 2.289
2017 1113004 43.392 408 416 403
2017 1113008 12.383 137 134 124
2017 1113012 27.106 252 252 249
2017 1113016 41.673 391 410 398
2017 1113020 39.585 364 391 373
2017 1113024 10.075 63 73 74
2017 1113028 24.083 199 205 209
2017 1113032 8.745 63 77 65
2017 1113036 18.143 170 170 143
2017 1113040 27.921 243 215 251
Table: ja
GKZ Jahr ja_name
1001000 2017 K X
1002000 2017 K Y
5370000 2017 L Z
5370004 2017 Z1
5370012 2017 Z2
5370016 2017 Z3
5370020 2017 Z4
I already got the calculation for one column (the first one: gesamt) in a function:
CREATE DEFINER=`DB`#`%` FUNCTION `Total_Amount_Funct`(
bev_ID int(11),
bev_Total int(11),
ja_name VARCHAR(255),
ja_jahr int(11)) RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE Total_Amount int(11);
DECLARE kreis int(11);
DECLARE Total_Sum int(11);
SET kreis = (bev_ID / 1000) ;
SET Total_Sum = (SELECT SUM(b.gesamt)
FROM bev as b, ja as j
WHERE b.GKZ = j.GKZ
AND b.Jahr = j.Jahr
AND j.Jahr = ja_jahr
AND (MOD(b.GKZ, 1000) <> 0)
AND (MOD(b.GKZ, 1000) != 0)
AND NOT (MOD(b.GKZ, 1000) = 0)
AND (b.GKZ BETWEEN (kreis*1000 + 1) AND (((kreis+1)*1000)-1))
AND j.ja_name IS NOT NULL);
SET Total_Amount = bev_Total-Total_Sum;
RETURN (Total_Amount);
END
This function can be called with the following select:
SELECT DISTINCT
bev.GKZ,
bev.Jahr,
bev.gesamt,
CASE WHEN (bev.GKZ % 1000 = 0) THEN
coalesce(Total_Amount_Funct(bev.GKZ, bev.gesamt, ja.ja_name, bev.Jahr), bev.gesamt)
ELSE bev.gesamt
END AS bev,
ja.ja_name
FROM
ja, bev
WHERE
bev.GKZ = ja.GKZ
AND bev.Jahr = ja.Jahr;
I really would like to apply the function for all columns of the table. Maybe as a stored procedure? Maybe as dynamic columns. I do not know. I have solved this problem in MS SQL with dynamic columns but I have the feeling that translating it will take more time than trying to complete the function as a Stored Procedure.
The name of the columns can be obtained by:
SELECT column_name
FROM information_schema.columns
WHERE table_name='bev'
and column_name not in ('Jahr','GKZ');
As Result it should be:
GKZ Jahr gesamt bev ja_name
1111000 2017 88.519 88.519 K X
1112000 2017 247.943 247.943 K Y
1113000 2017 253.106 101.350 L Z
1113004 2017 43.392 43.392 Z1
1113012 2017 27.106 27.106 Z2
1113016 2017 41.673 41.673 Z3
1113020 2017 39.585 39.585 Z4
As you are using the column only in the SUM, you could pass the column name as parameter and use CASE-statement to pick the column accordingly. Something like:
CREATE FUNCTION `Total_Amount_Funct`(
bev_ID decimal(8,3),
bev_Total int,
ja_name VARCHAR(255),
ja_jahr int,
in_col varchar(10)
)
RETURNS int
DETERMINISTIC
BEGIN
DECLARE Total_Amount int(11);
DECLARE Total_Sum int(11);
SELECT
SUM(
case
when in_col='gesamt' then b.gesamt
when in_col='A' then b.A
when in_col='B' then b.B
when in_col='C' then b.C
end
) into Total_Sum
FROM bev as b
join ja as j on b.GKZ = j.GKZ AND b.Jahr = j.Jahr
WHERE
MOD(b.GKZ, 1000) != 0
AND b.GKZ BETWEEN bev_ID+1 AND bev_ID+999
AND j.ja_name IS NOT NULL
SET Total_Amount = bev_Total-Total_Sum;
RETURN (Total_Amount);
END
And then call the function with column name and correct value:
Total_Amount_Funct(bev.GKZ, bev.gesamt, ja.ja_name, bev.Jahr, 'gesamt'),
Total_Amount_Funct(bev.GKZ, bev.A, ja.ja_name, bev.Jahr, 'A')
...
Note that calling a function which makes a query will serialize your SQL (calling the function on each row causes the function query to be executed on each row). This will hurt the query performance.
slaakso,
thank you very much for your answer. You are from today my idol :-).
Thanks Thanks.
I have maybe one performance Question.
It is posible to write the function for all columns of the table bev. We can copy the column names in a temporary table:
CREATE TEMPORARY TABLE listColumns(
Columns_ID MEDIUMINT NOT NULL AUTO_INCREMENT ,
Columnsnamen varchar(256) ,
PRIMARY KEY (Columns_ID)
);
Readed from the System Information:
insert into listColumns (Columnsnamen)
SELECT column_name
FROM information_schema.columns
WHERE table_name='bev'
and column_name not in ('Jahr','GKZ');
This Table looks like:
Columns_ID Columnsnamen
1 gesamt
2 A
3 B
4 C
5
6
In such a way, that it is not necessary to mentione every column name (the table contains about 100 columns). Maybe with a cursor over the Columns_ID?
It woul be great if you have another advice for me.
Thank you and kind regads
Ana

Checking to see if today is in the scheduled day utilizing a binary mapping table in SQL

I am pulling XML data from a 3rd party application using SQL Server 2008 (which I only have read-only access to the DB) and it stores the day or days of the week a job is supposed to run in one of those XML fields.
SQL uses a recursive day code of Sunday=1, Monday=2, Tuesday=4, Wednesday=8, Thursday=16, Friday=32, Saturday=64.
I am pulling the day from this XML field like the following.
case
when (job.SJDefn.value('(schedules/schedule/name)[1]', 'varchar(30)') ) like '%Week%'
then job.SJDefn.value('(/schedules/schedule/recurring/date/week/day_of_week)[1]', 'int')
else 0
end as JDOW,
I was originally utilizing the this to determine the current date of the week as but the values were obviously not compatible.
DATEPART(dw, getdate()) AS CDOW, -- Sun 1 Mon 2 Tue 3 Wed 4 Thu 5 Fri 6 Sat 7`
So I moved to:
case DATEPART(dw, getdate())
when 1 then 1 -- Sunday (1=1)
when 2 then 2 -- Monday (2=2)
when 3 then 4 -- Tueday (3=4
when 4 then 8 -- Wednesday (4=8)
when 5 then 16 -- Thursday (5=16)
when 6 then 32 -- Friday (6=32)
when 7 then 64 -- Saturday (7=64)
else NULL
end as CDOW,
The challenge is that it is an easy translation when the job just runs one day of a week.. but what about Monday/Wednesday/Friday well that is 42 which is an aggregate of the days Monday (2) + Wednesdays (8) + Friday (32).
I could translate this to text like in this question and do a string compare to a temp table but that seems inefficient.
I know that there is a table that can be built like this code to build a comparison table and I've checked the SQL Server Agent documentation (which this isn't but it is quite similar.
It seems like all possible combinations for Sunday - Saturday are basically a bitmap ranged from 1-127.. such as 42 = 0010 1010 which could be an on/off values for each day (first position always 0, 127 = 0111 111) and with that.
Position 1 = Always 0 ; binary 0000 0000
Position 2 = Sunday 1 ; binary 0000 0001
Position 3 = Monday 2 ; binary 0000 0010
Position 4 = Tueday 4 ; binary 0000 0100
Position 5 = Wednesday 8 ; binary 0000 1000
Position 6 = Thursday 16 ; binary 0001 0000
Position 7 = Friday 32 ; binary 0010 0000
Position 8 = Saturday 64 ; binary 0100 0000
I am thinking about how to potentially use a bitwise & operator but it compares the entire bit for an exact match and not a single position as I understand it so not thinking it will accomplish exactly what I want.
What I want is if the current day is in the schedule I get a true / false result from the comparison. I don’t care about interpreting the values into plain English.. For example if the string was 0011 1110 (Monday - Friday), then if the current day value is the equivalent of 0000 0010 (Monday) I be get true. If it was Sunday (0000 0001) it would be false if the reference was that 0010 1110.
I would really think there is a much simpler way of simply checking if the current day falls into the configuration in a few lines vs. building a temporary table to compare against.
So my question: given the information above, is there a simple function / query that I can execute to compare the two and return a boolean result (0/1 or Y/N) if the the current day matches the schedule?
This will give you a 1/0 result for the current date given a schedule bitmap:
declare #Today as Date = GetDate();
-- Assuming that ##DateFirst is correctly set:
declare #DoW as Int = DatePart( weekday, #Today );
-- Shift a bit to the appropriate position.
declare #Mask as Int = Power( 2, #DoW - 1 );
-- Sample schedule bitmap.
declare #Schedule as Int = 42;
-- Sign is used to convert the result of the bitwise-and to a 0 or 1.
-- Any positive value, indicating the corresponding bit is set, will return 1.
-- If there is no match, the result will be zero.
select #Today as Today, #DoW as Dow, #Mask as Mask, #Schedule as Schedule,
Sign( #Schedule & #Mask ) as IsScheduledToday;
As a professor once said, "you're always off by one in this business." It may need a tweak, but should be close.
It's a little difficult to tell exactly what you're trying to do here. You've explained the problem, but didn't provide any desired output. Since you have read-only access, however, I assume you're only interested in querying the data.
However, if you have an integer like 42, and you want to test bitwise if the bit for Monday is set (that is, 2's place), then you do this:
42 & 2 = 2
If you want to display days of the week you could do something like:
SELECT
CASE WHEN JDOW & 1 = 1 THEN 'U' ELSE '' END
+ CASE WHEN JDOW & 2 = 2 THEN 'M' ELSE '' END
+ CASE WHEN JDOW & 4 = 4 THEN 'T' ELSE '' END
+ CASE WHEN JDOW & 8 = 8 THEN 'W' ELSE '' END
+ CASE WHEN JDOW & 16 = 16 THEN 'R' ELSE '' END
+ CASE WHEN JDOW & 32 = 32 THEN 'F' ELSE '' END
+ CASE WHEN JDOW & 64 = 64 THEN 'S' ELSE '' END AS scheduled_days
FROM (VALUES (42),(84),(96), (4)) UnnamedTable (JDOW)
If you want you could create another table:
CREATE TABLE BitwiseWeekDay (
code tinyint primary key not null,
day_name nvarchar(10) not null,
day_short_name nvarchar(4) not null,
day_code nvarchar(1) not null
)
INSERT INTO BitwiseWeekDay VALUES
(1,'Sunday','Sun','U'),
(2,'Monday','Mon','M'),
(4,'Tuesday','Tue','T'),
(8,'Wednesday','Wed','W'),
(16,'Thurday','Thur','R'),
(32,'Friday','Fri','F'),
(64,'Saturday','Sat','U')
SELECT u.JDOW,
b.code,
b.day_name
FROM (VALUES (42),(84),(96), (4)) u (JDOW)
INNER JOIN BitwiseWeekDay b
ON u.JDOW & b.code = b.code
ORDER BY u.JDOW, b.code
But, I don't really know what you're looking for.

standard unambiguos format [R] MySQL imported data

OK, to set the scene, I have written a function to import multiple tables from MySQL (using RODBC) and run randomForest() on them.
This function is run on multiple databases (as separate instances).
In one particular database, and one particular table, the "error in as.POSIXlt.character(x, tz,.....): character string not in a standard unambiguous format" error is thrown. The function runs on around 150 tables across two databases without any issues except this one table.
Here is a head() print from the table:
MQLTime bar5 bar4 bar3 bar2 bar1 pat1 baXRC
1 2014-11-05 23:35:00 184 24 8 24 67 147 Flat
2 2014-11-05 23:57:00 203 184 204 67 51 147 Flat
3 2014-11-06 00:40:00 179 309 49 189 75 19 Flat
4 2014-11-06 00:46:00 28 192 60 49 152 147 Flat
5 2014-11-06 01:20:00 309 48 9 11 24 19 Flat
6 2014-11-06 01:31:00 24 177 64 152 188 19 Flat
And here is the function:
GenerateRF <- function(db, countstable, RFcutoff) {
'load required libraries'
library(RODBC)
library(randomForest)
library(caret)
library(ff)
library(stringi)
'connection and data preparation'
connection <- odbcConnect ('TTODBC', uid='root', pwd='password', case="nochange")
'import count table and check if RF is allowed to be built'
query.str <- paste0 ('select * from ', db, '.', countstable, ' order by RowCount asc')
row.counts <- sqlQuery (connection, query.str)
'Operate only on tables that have >= RFcutoff'
for (i in 1:nrow (row.counts)) {
table.name <- as.character (row.counts[i,1])
col.count <- as.numeric (row.counts[i,2])
row.count <- as.numeric (row.counts[i,3])
if (row.count >= 20) {
'Delete old RFs and DFs for input pattern'
if (file.exists (paste0 (table.name, '_RF.Rdata'))) {
file.remove (paste0 (table.name, '_RF.Rdata'))
}
if (file.exists (paste0 (table.name, '_DF.Rdata'))) {
file.remove (paste0 (table.name, '_DF.Rdata'))
}
'import and clean data'
query.str2 <- paste0 ('select * from ', db, '.', table.name, ' order by mqltime asc')
raw.data <- sqlQuery(connection, query.str2)
'partition data into training/test sets'
set.seed(489)
index <- createDataPartition(raw.data$baXRC, p=0.66, list=FALSE, times=1)
data.train <- raw.data [index,]
data.test <- raw.data [-index,]
'find optimal trees to grow (without outcome and dates)
data.mtry <- as.data.frame (tuneRF (data.train [, c(-1,-col.count)], data.train$baXRC, ntreetry=100,
stepFactor=.5, improve=0.01, trace=TRUE, plot=TRUE, dobest=FALSE))
best.mtry <- data.mtry [which (data.mtry[,2] == min (data.mtry[,2])), 1]
'compress df'
data.ff <- as.ffdf (data.train)
'run RF. Originally set to 1000 trees but M1 dataset is to large for laptop. Maybe train at the lab?'
data.rf <- randomForest (baXRC~., data=data.ff[,-1], mtry=best.mtry, ntree=500, keep.forest=TRUE,
importance=TRUE, proximity=FALSE)
'generate and print variable importance plot'
varImpPlot (data.rf, main = table.name)
'predict on test data'
data.test.pred <- as.data.frame( predict (data.rf, data.test, type="prob"))
'get dates and name date column'
data.test.dates <- data.frame (data.test[,1])
colnames (data.test.dates) <- 'MQLTime'
'attach dates to prediction df'
data.test.res <- cbind (data.test.dates, data.test.pred)
'force date coercion to attempt negating unambiguous format error '
data.test.res$MQLTime <- format(data.test.res$MQLTime, format = "%Y-%m-%d %H:%M:%S")
'delete row names, coerce to dataframe, generate row table name and export outcomes to MySQL'
rownames (data.test.res)<-NULL
data.test.res <- as.data.frame (data.test.res)
root.table <- stri_sub(table.name, 0, -5)
sqlUpdate (connection, data.test.res, tablename = paste0(db, '.', root.table, '_outcome'), index = "MQLTime")
'save RF and test df/s for future use; save latest version of row_counts to MQL4 folder'
save (data.rf, file = paste0 ("C:/Users/user/Documents/RF_test2/", table.name, '_RF.Rdata'))
save (data.test, file = paste0 ("C:/Users/user/Documents/RF_test2/", table.name, '_DF.Rdata'))
write.table (row.counts, paste0("C:/Users/user/AppData/Roaming/MetaQuotes/Terminal/71FA4710ABEFC21F77A62A104A956F23/MQL4/Files/", db, "_m1_rowcounts.csv"), sep = ",", col.names = F,
row.names = F, quote = F)
'end of conditional block'
}
'end of for loop'
}
'close all connection to MySQL'
odbcCloseAll()
'clear workspace'
rm(list=ls())
'end of function'
}
At this line:
data.test.res$MQLTime <- format(data.test.res$MQLTime, format = "%Y-%m-%d %H:%M:%S")
I have tried coercing MQLTime using various functions including: as.character(), as.POSIXct(), as.POSIXlt(), as.Date(), format(), as.character(as.Date())
and have also tried:
"%y" vs "%Y" and "%OS" vs "%S"
All variants seem to have no effect on the error and the function is still able to run on all other tables. I have checked the table manually (which contains almost 1500 rows) and also in MySQL looking for NULL dates or dates like "0000-00-00 00:00:00".
Also, if I run the function line by line in R terminal, this offending table is processed without any problems which just confuses the hell out me.
I've exhausted all the functions/solutions I can think of (and also all those I could find through Dr. Google) so I am pleading for help here.
I should probably mention that the MQLTime column is stored as varchar() in MySQL. This was done to try and get around issues with type conversions between R and MySQL
SHOW VARIABLES LIKE "%version%";
innodb_version, 5.6.19
protocol_version, 10
slave_type_conversions,
version, 5.6.19
version_comment, MySQL Community Server (GPL)
version_compile_machine, x86
version_compile_os, Win32
> sessionInfo()
R version 3.0.2 (2013-09-25)
Platform: i386-w64-mingw32/i386 (32-bit)
Edit: Str() output on the data as imported from MySQl showing MQLTime is already in POSIXct format:
> str(raw.data)
'data.frame': 1472 obs. of 8 variables:
$ MQLTime: POSIXct, format: "2014-11-05 23:35:00" "2014-11-05 23:57:00" "2014-11-06 00:40:00" "2014-11-06 00:46:00" ...
$ bar5 : int 184 203 179 28 309 24 156 48 309 437 ...
$ bar4 : int 24 184 309 192 48 177 48 68 60 71 ...
$ bar3 : int 8 204 49 60 9 64 68 27 192 147 ...
$ bar2 : int 24 67 189 49 11 152 27 56 437 67 ...
$ bar1 : int 67 51 75 152 24 188 56 147 71 0 ...
$ pat1 : int 147 147 19 147 19 19 147 19 147 19 ...
$ baXRC : Factor w/ 3 levels "Down","Flat",..: 2 2 2 2 2 2 2 2 2 3 ...
So I have tried declaring stringsAsfactors = FALSE in the dataframe operations and this had no effect.
Interestingly, if the offending table is removed from processing through an additional conditional statement in the first 'if' block, the function stops on the table immediately preceeding the blocked table.
If both the original and the new offending tables are removed from processing, then the function stops on the table immediately prior to them. I have never seen this sort of behavior before and it really has me stumped.
I watched system resources during the function and they never seem to max out.
Could this be a problem with the 'for' loop and not necessarily date formats?
There appears to be some egg on my face. The table following the table where the function was stopping had a row with value '0000-00-00 00:00:00'. I added another statement in my MySQL function to remove these rows when pre-processing the tables. Thanks to those that had a look at this.

how to create an sql view based on calculated vales?

Hie lets assume we have the following table
TABLE NAME : DRINGE
__________________________________________________
ID PRODUCT MACHINE MASS STATE
01 1.76ann HRB 50 inlet
02 1.76ann HRB 38 inlet
03 2.55ann GUDO 45 outlet
04 95mm x 4 GUDO 36 dispatched
___________________________________________________
And the following formula:
(inlet –outlet ) +outlet – dispatched = [resulted displayed to new view]
And the values to be substituted are:
INLET = 50 , 38
OUTLET=45
DISPATCHED = 36
So substituting in the above formula
[(inlet –outlet ) +outlet – dispatched = [resulted displayed to new view]
We get this
(50+38 – 45 ) + 45 – 36 = 52
What I want is for the result ie 52 to be displayed in an sql view like the following view
Dringe VIEW
_____________
Total_summary|
_____________|
52 |
_____________|
.
Does anyone have any idea of an sql query I can use to do this ?
I rily need your help am stuck again, thanx in advance.
The below will follow your formula
CREATE VIEW DRINGEView AS
SELECT sum(case when state = 'inlet' then mass else 0 end) -
sum(case when state = 'outlet' then mass else 0 end)+
sum(case when state = 'outlet' then mass else 0 end) -
sum(case when state = 'dispatched' then mass else 0 end) AS Total_summary
FROM dringe
But adding outlet then subtracting outlet would be redundant. The brackets in your formula would also be redundant as all of your operators are addition/subtraction, could one of your operators be multiplication/division?
you can just add those calculations to your query in something like
(40+50+fieldName*anotherFieldName) AS calculation
and you can even use sub tables like
(40+50+(SELECT fieldName FROM anotherTable WHERE someValue) AS calculation
create view dringe_view as
select (sum(inlet) – sum(outlet) ) +sum(outlet) – sum(dispatched ) as total_summary
from tab
But your claculation can be further simplified (remove outlet - outlet) to (inlet – dispatched)