I have table like this:
table's name: registrationdate
I want to get the maximum value on last_update's column, so I use this query:
SELECT idtemp, max(last_update) FROM `registrationdate`
then the result will be like this:
and I have table like this:
table's name: temp
then I want to compare max(last_update) in registrationdate's table and generatedtime in temp's table
this is the schema:
what may I do so that I can get table like that? Thanks in advance.
Fyi, idtemp in registrationdate's table = id in temp's table
Please try the following...
SELECT ID AS ID,
generatedTime AS generatedTime,
tempTable AS tempTable,
CASE
WHEN generatedTime < maxLastUpdate THEN
'not'
ELSE
'update'
END AS UPDATEorNot
FROM temp
JOIN ( SELECT idtemp AS idtemp,
MAX( last_update ) AS maxLastUpdate
FROM registrationdate
GROUP BY idtemp
) AS maxLastUpdateFinder ON temp.ID = maxLastUpdateFinder.idtemp;
Assumptions
That records in temp that do not have at least one matching record in registrationdate do not need to be included in the output.
That the comparison and sample data are valid and the sample output's UPDATEorNot field should read not.
Explanation
This statement starts with a subquery that finds each unique value of idtemp in registrationdate and the most recent value of last_update associated with it.
An INNER JOIN is then performed between temp and the results of the subquery so that each record in temp with at least one corresponding record in registrationdate is retained and has its corresponding most recent value of last_update appended to it.
The fields from temp are then SELECTed, and a CASE statement used to determine the value to be selected for each record's UPDATEorNot field.
Please note that my statement will return not when the comparison that you supplied is applied to the sample data. If you want update to be chosen then you will need to change your comparison from generatedTime < max( last_update ) to generatedTime > max( last_update ), or to correct your sample data.
Testing
My statement was tested against a sample database created using the following script...
CREATE TABLE registrationdate
(
last_update DATETIME,
idtemp INT
);
INSERT INTO registrationdate ( last_update,
idtemp )
VALUES ( '2017-05-12 14:20:58', 0 ),
( '2017-05-12 14:20:58', 0 ),
( '2017-05-12 14:20:58', 0 ),
( '2017-05-12 14:20:58', 0 ),
( '2017-05-12 14:20:58', 0 ),
( '2017-05-12 14:20:58', 0 ),
( '2017-05-12 14:20:58', 0 ),
( '2017-05-12 14:20:58', 0 ),
( '2017-05-12 14:20:58', 0 ),
( '2017-05-12 14:20:58', 0 ),
( '2017-05-12 14:20:58', 0 ),
( '2017-05-12 14:20:58', 0 );
CREATE TABLE temp
(
ID INT,
generatedTime DATETIME,
tempTable VARCHAR( 50 )
);
INSERT INTO temp ( ID,
generatedTime,
tempTable )
VALUES ( 0, '2017-05-01 14:37:00', 'temp_pelamardoktorjk' ),
( 2, '2017-05-01 14:37:00', 'temp_pelamarmagisteripk' ),
( 3, '2017-05-01 14:38:00', 'temp_pelamarmagisterstatusinstitusi' ),
( 4, '2017-05-01 14:38:00', 'temp_pelamarmagisterusia' ),
( 5, '2017-05-01 14:38:00', 'temp_pelamarmagisterstatusinstansi' );
If you have any questions or comments, then please feel free to post a Comment accordingly.
Appendix 1
The following is an alternative form of the above statement...
SELECT ID AS ID,
generatedTime AS generatedTime,
tempTable AS tempTable,
CASE
WHEN generatedTime < MAX( last_update ) THEN
'not'
ELSE
'update'
END AS UPDATEorNot
FROM temp
JOIN registrationdate ON temp.ID = registrationdate.idtemp
GROUP BY ID,
generatedTime,
tempTable;
Appendix 2
Please try the following attempted rewrite of the linked to code...
SELECT
generatedTime AS generatedTime,
tempTable AS tempTable,
CASE
WHEN ( ( generatedTime < ( SELECT MAX( last_update ) AS maxPelamarmhsdoktor
FROM pelamarmhsdoktor ) ) OR
( generatedTime < ( SELECT MAX( last_update ) AS maxAkdmstmayor
FROM akdmst_mayor ) ) OR
( generatedTime < ( SELECT MAX( last_update ) AS maxIpbmstdepartemen
FROM ipbmst_departemen ) ) OR
( generatedTime < ( SELECT MAX( last_update ) AS maxIpbmstfakultas
FROM ipbmst_fakultas ) ) OR
( generatedTime < ( SELECT MAX( last_update ) AS maxIpbrefjeniskelamin
FROM ipbref_jeniskelamin ) ) OR
( generatedTime < ( SELECT MAX( last_update ) AS maxJenisinstansi
FROM jenisinstansi ) ) OR
( generatedTime < ( SELECT MAX( last_update ) AS maxJenisinstitusi
FROM jenisinstitusi
) ) ) THEN
'Yes'
ELSE
'No'
END AS NeedsToUpdateOrNot
FROM generatedTime;
Related
I am new to this and i am wondering how to input data into SSRS table and auto generate for the subsequent months. This is the format of the table.
Appreciated for any help given.
You can generate a date range using the following SQL
DECLARE #date_start AS DATETIME
SET #date_start = '01-DEC-2017'
;WITH
finalvalues
AS
(
SELECT tbl.* FROM (VALUES
( '01-Dec-2017', 6414.6563, 429.6846, -1390.8474)
, ( '02-Dec-2017', 6476.6563, 432.751, -1312.4928)
, ( '03-Dec-2017', 6538.6563, 435.8174, -1234.1382)
, ( '04-Dec-2017', 6600.6563, 438.8838, -1155.7836)
, ( '05-Dec-2017', 6662.6563, 441.9502, -1077.429)
, ( '06-Dec-2017', 6724.6563, 445.0166, -999.074399999999)
, ( '07-Dec-2017', 6786.6563, 448.083, -920.719799999999)
, ( '08-Dec-2017', 6848.6563, 451.1494, -842.365199999999)
, ( '09-Dec-2017', 6910.6563, 454.2158, -764.010599999999)
, ( '10-Dec-2017', 6972.6563, 457.2822, -685.655999999999)
, ( '11-Dec-2017', 7034.6563, 460.3486, -607.301399999999)
, ( '12-Dec-2017', 7096.6563, 463.415, -528.946799999999)
, ( '13-Dec-2017', 7158.6563, 466.4814, -450.592199999999)
, ( '14-Dec-2017', 7220.6563, 469.5478, -372.2376)
, ( '15-Dec-2017', 7282.6563, 472.6142, -293.883)
, ( '16-Dec-2017', 7344.6563, 475.6806, -215.5284)
) tbl ([Date], [IncLoad], [ITLoad], [RH])
)
,
manufactured_dates
AS
(
SELECT
day_date = DATEADD(day, dte.[number], #date_start)
FROM
master.dbo.spt_values AS dte
WHERE
1=1 -- <-- used in testing to be able to comment out other clauses below
AND dte.[type] = 'P'
AND dte.[number] <= 365 -- <-- filter how many rows you want to see here
)
SELECT
'Date' = md.[day_date]
, 'IncLoad' = AVG(incload)
, 'ITLoad' = AVG(ITLoad)
FROM
finalvalues AS fv
FULL OUTER JOIN manufactured_dates AS md ON md.[day_date] = fv.[Date]
GROUP BY
md.[day_date]
$sql = "SELECT max( `reg_date` ) AS endtime, min( `reg_date` ) AS starttime, sum( `distance` ) AS total FROM `user_distance` WHERE user_id =8 GROUP BY CAST( `reg_date` AS DATE )";
$sql1="SELECT CAST( `reg_date` AS DATE ) AS date, count( * ) AS customer_total FROM `customer` WHERE user_id =8 GROUP BY CAST( `reg_date` AS DATE )";
I am getting perfect result for this two queries, but I want to combine the results of this two queries.
drop temporary table if exist temp1;
create temporary table temp1
SELECT max( `reg_date` ) AS endtime, min( `reg_date` ) AS starttime, sum( `distance` ) AS total
FROM `user_distance`
WHERE user_id =8 GROUP BY CAST( `reg_date` AS DATE )"
union
SELECT CAST( `reg_date` AS DATE ) AS date,''as starttime, count( * ) AS customer_total
FROM `customer`
WHERE user_id =8 GROUP BY CAST( `reg_date` AS DATE )";
select * from temp1;
I'm new to SQL and probably going about this the wrong way but could you help?
I need to create a VIEW in MySQL but I can't figure out how to combine these two SQL statements, as VIEWs do not accept multiple SELECTS or Variables.
NB: the second statement works perfectly when replacing the #numberOfGames var with the correct number (manually calculated).
First statement - to return the total number of games for year:
SELECT COUNT( id ) INTO #numberOfGames FROM tblgames WHERE gdate LIKE '2014%';
Second statement - to create VIEW data:
SELECT
p.player AS player,
COUNT( c.gid ) AS gameCount,
SUM( c.cash ) AS cash,
ROUND( AVG( c.cash ), 2 ) AS avg,
SUM( ( CASE WHEN ( c.wotn > 0 ) THEN c.wotn ELSE 0 END ) ) AS wotn,
SUM( ( CASE WHEN ( c.cash > 0 ) THEN c.cash ELSE 0 END ) ) AS cashWon,
SUM( ( CASE WHEN ( c.cash < 0 ) THEN c.cash ELSE 0 END ) ) AS cashLost,
ROUND( AVG( ( CASE WHEN ( c.cash >= 0 ) THEN c.cash END ) ),2 ) AS avgWin,
ROUND( AVG( ( CASE WHEN ( c.cash < 0 ) THEN c.cash END ) ),2 ) AS avgLoss,
IF(
( ( COUNT( c.pid ) > ( #numberOfGames / 3 ) ) AND ( COUNT( c.pid ) > 2 ) ),
ROUND( ( ( AVG( c.cash ) * 10 ) + 200 ), 2 ),
ROUND( AVG( c.cash ), 2 )
) AS sortingPoints
FROM tblplayers p
LEFT JOIN tblcash c ON p.id = c.pid
LEFT JOIN tblgames g ON g.id = c.gid
WHERE c.cash IS NOT NULL AND g.gdate LIKE '2014%'
GROUP BY c.pid
ORDER BY sortingPoints DESC;
I'm using the #numberOfGames vars for a simple maths equation that checks it a player has played more than a third of the total games in the year.
I hope someone can help point me it the right direction.
You are missing the point of what a view does.
You can't save multiple statements in one view. It's like trying to save two tables in one table. It's not possible.
What you need to do is, run your first Select, exactly as you have it. Save it as a view. Then you can use that result set as if it were any other live table, and join it to other tables in subsequent Select statements.
From a MySQL database I am seeking to create a column from a field that meets conditions.
This works:
DROP TABLE IF EXISTS report4;
create TABLE report4 as (
select
orders_products.orders_id,
MAX( IF(products_id = 1, final_price, "-") ) AS Membership,
MAX( IF(products_id = 12, final_price, "-" ) ) AS Donation,
MAX( IF( products_id = 16, final_price, "-" ) ) AS AHCD
from orders_products
Group by orders_id M);
select * from report4;
But I also have other product_id that I wish to inject into the new columns of Membership and Donation.
Product with IDs 2,3,4,5,6,7,8,9,10,11 are to go into Membership.
Product with IDs 13,14,15,17,18 are to go into Donation.
It is this secondary part I cannot make work. Thoughts on what I need to do.
Use this syntax:
MAX( IF(products_id IN (2,3,4,5,6,7,8,9,10,11), final_price, "-") )
Change your inner query to products_id IN (....) as shown below
DROP TABLE IF EXISTS report4;
create TABLE report4 as ( select
orders_products.orders_id,
MAX( IF(products_id IN ( 1,2,3,4,5,6,7,8,9,10,11 ), final_price, "-") ) AS Membership,
MAX( IF(products_id IN ( 12,13,14,15,17,18 ), final_price, "-" ) ) AS Donation,
MAX( IF( products_id = 16, final_price, "-" ) ) AS AHCD
from orders_products
Group by orders_id M);
select * from report4;
Alternatively, you can also use products_id = 1 OR products_id = 2 OR ... instead of IN
The answer by #Lobo works for what you are looking for. However, if you have to add any more products, you will have to constantly redo the query, and it is not scalable. You should change your database to store a products_type column somewhere, allowing you to simple recategorise a product when you want and have the query run correctly every time.
Add a table called products_types and you can use this query instead:
select
orders_products.orders_id,
MAX( IF(pt.types_id = 1, final_price, "-") ) AS Membership,
MAX( IF(pt.types_id = 2, final_price, "-" ) ) AS Donation,
MAX( IF(pt.types_id = 3, final_price, "-" ) ) AS AHCD
from orders_products
join products_types pt on (pt.products_id = orders_products.products_id)
group by orders_id
The table definition for types I used was:
CREATE TABLE `products_types` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`products_id` int(11) DEFAULT NULL,
`types_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
I have a table that contains Customers,Anchor Date(original sales date),Call Frequency(7,14 or 21 days). I need to use the customers specific Anchor date and Frequency to create and add future call records to a table until a defined end date. I am using SQL 2008
This looks like a start:
declare #Customers as Table ( CustomerId Int Identity, AnchorDate Date, CallFrequency Int );
insert into #Customers ( AnchorDate, CallFrequency ) values
( '20130101', 7 ), ( '20130102', 14 ), ( '20130103', 21 ),
( '20130104', 7 ), ( '20130105', 14 ), ( '20130106', 21 ),
( '20130107', 7 ), ( '20130108', 14 ), ( '20130109', 21 );
select *
from #Customers
declare #EndDate as Date = '20131231';
declare #Today as Date = SysDateTime();
with FutureCalls as (
select CustomerId, DateAdd( day, ( DateDiff( day, AnchorDate, #Today ) / CallFrequency + 1 ) * CallFrequency, AnchorDate ) as CallDate, CallFrequency
from #Customers
union all
select CustomerId, DateAdd( day, CallFrequency, CallDate ), CallFrequency
from FutureCalls
where DateAdd( day, CallFrequency, CallDate ) <= #EndDate
)
select *
from FutureCalls
order by CallDate, CustomerId
option ( MaxRecursion 0 )