1. Name Explanation
Constant: Treat the result set of some queries as a variable, and directly participate in other calculations after the results come out, and do not need to query the results again.
Second, very practical sql statement
1. Iterative query
Table Structure
CREATE TABLE `product` ( `id` int(11) NOT NULL auto_increment COMMENT 'id', `productName` varchar(100) NOT NULL COMMENT 'product name', `productPrice` int(11) NOT NULL COMMENT 'Product Price', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8
Test Data
insert into `product` (`id`, `productName`, `productPrice`) values('1','产品1','23'); insert into `product` (`id`, `productName`, `productPrice`) values('2','产品2','34'); insert into `product` (`id`, `productName`, `productPrice`) values('3','产品3','38'); insert into `product` (`id`, `productName`, `productPrice`) values('4','产品4','45'); insert into `product` (`id`, `productName`, `productPrice`) values('5','产品5','78'); insert into `product` (`id`, `productName`, `productPrice`) values('6','产品1','65');
The effect is as shown in the figure:
figure 1
figure 2
As can be seen from the above query results, the rule for the value of the totalprice field is the sum of the totalprice from the first record to the current record, but this method is not efficient, especially when there are many records.
From the analysis of the query results in Figure 2, it can be seen that this result is still a summation operation, but instead of summing all records or grouping the summation, the summation is performed in an iterative manner. The summation formula is as follows: The totalprice value of the current record = the productPrice value of the current record + the totalprice value of the previous record. The totalprice value of the previous record can also be regarded as the sum of the productPrice values of all previous records of the current record. Therefore, each record can be summed (using the sum function), but the sum of the productPrice of the current record and the previous record is required, as in the following SQL statement:
SELECT a.id,a.productPrice,(SELECT SUM(productPrice) FROM product b WHERE b.id <= a.id ) AS totalprice FROM product a;
2. The application of constants in sql statements
create table
CREATE TABLE `r_statistics_hour` ( `id` bigint(50) NOT NULL auto_increment, `createDate` date default NULL, `modifyDate` date default NULL, `timePatternString` varchar(20) default NULL COMMENT 'Statistical time type', `salesAmount` double default NULL COMMENT 'Sales', `shoppersTraffic` double default NULL COMMENT 'customer traffic', `empWorkHoursPer` double default NULL COMMENT 'employee working hours ratio', `avgSalesAmount` double default NULL COMMENT 'Average transaction amount', `turnoverAmountRate` double default NULL COMMENT 'turnover rate', `storeid` int(11) default NULL, `regionId` int(11) default NULL, `turnoverAmount` int(11) default NULL COMMENT 'turnoverAmount', `empWorkTime` double default NULL COMMENT 'employee working hours', `businessOpportunities` int(11) default NULL COMMENT 'Business Opportunities (people outside the store)', `giveUpRate` double default NULL COMMENT 'giveUpRate', `residenceTime` double default NULL COMMENT 'Average residence time', `transactionScale` double default NULL COMMENT 'Transaction scale', `estimatedVisits` int(11) default NULL COMMENT 'estimated sales', `timestring` varchar(32) default NULL, PRIMARY KEY (`id`), UNIQUE KEY `unique_statistics` (`timestring`,`storeid`) ) ENGINE=InnoDB AUTO_INCREMENT=30970 DEFAULT CHARSET=utf8
Refer to the sql statement
SELECT DATE_FORMAT( CONCAT(timePatternString, '0000'), '%H' ) hours, SUM(salesAmount) salesAmount, AVG(b.salesAmount12) salesAmount12 FROM r_statistics_hour a, -- When there is a variable, the call statement can be used as a constant and added to the above query statement (SELECT SUM(salesAmount) salesAmount12 FROM r_statistics_hour WHERE LEFT(timePatternString, 8) >= 20150830 AND LEFT(timePatternString, 8) <= 20150926 AND (storeid = 47 OR regionId = 47)) b WHERE LEFT(timePatternString, 8) >= 20150830 AND LEFT(timePatternString, 8) <= 20150926 AND (storeid = 47 OR regionId = 47) GROUP BY DATE_FORMAT( CONCAT(timePatternString, '0000'), '%H' )
3. Use the intercepted string (LOCATE(CONCAT(store_id,','), CONCAT(ca.`STOREIDS`,','))>0) and ifnull in the sql statement
SELECT *, -- Calculate the number of days between two dates (TO_DAYS(end_time) - TO_DAYS(start_time) + 1) dayNum, -- Get the number of stores (field length - separator length) + 1 LENGTH(STOREIDS) - LENGTH(REPLACE(STOREIDS,',',''))+1 storeNum, -- The current passenger flow divided by the chain passenger flow * 100 retains two decimal places, when judging whether it is empty, if it is empty, set it to zero IFNULL(FORMAT(((enters - entersHb) / entersHb)*100,2),0) rateHb, IFNULL(FORMAT(((enters - entersTb) / entersTb)*100,2),0) rateTb, FORMAT((SPEND /(enters - entersHb)),2) costAvgHb, FORMAT((SPEND /(enters - entersTb)),2) costAvgTb FROM ( SELECT *, -- LOCATE(CONCAT(store_id,','),CONCAT(ca.`STOREIDS`,','))>0 Determine whether the value of store_id is in ca.`STOREIDS`; DATE_FORMAT(ca.START_TIME, '%Y %m%d') date formatting IFNULL((SELECT SUM(ENTERS) FROM t_statistic_day WHERE LOCATE(store_id,CONCAT(ca.`STOREIDS`,','))>0 AND DATE >= DATE_FORMAT(ca.START_TIME, '%Y%m%d') AND DATE <= DATE_FORMAT(ca.END_TIME, '%Y%m%d')),0) enters, IFNULL((SELECT SUM(ENTERS) FROM t_statistic_day WHERE LOCATE(store_id,CONCAT(ca.`STOREIDS`,','))>0 AND DATE >= DATE_FORMAT(ca.START_HB_TIME, '%Y%m%d') AND DATE <= DATE_FORMAT(ca.END_HB_TIME, '%Y%m%d')),0) entersHb, IFNULL((SELECT SUM(ENTERS) FROM t_statistic_day WHERE LOCATE(store_id,CONCAT(ca.`STOREIDS`,','))>0 AND DATE >= DATE_FORMAT(ca.START_TB_TIME, '%Y%m%d') AND DATE <= DATE_FORMAT(ca.END_TB_TIME, '%Y%m%d')),0) entersTb FROM t_campaigns ca WHERE STAFF_ID = 1) tempA
Description: LOCATE(CONCAT(store_id,','),CONCAT(ca.`STOREIDS`,','))>0 means that store_id exists in the ca.`STOREIDS` string.
4. Use Uncle Time as the conditional time to compare, and compare the current time data with the comparative time data
-- The consciousness of sql is to get the current date, the total passenger flow on the current date, the average passenger flow of each store on the current date, and compare the passenger flow on the date and the change rate of the passenger flow SELECT DATE_FORMAT(dq.date,'%Y/%m/%d') currentDate,dq.enters enters,dq.entersAvg entersAvg,DATE_FORMAT(tb.date,'%Y/%m/%d') contrastDate,tb.enters entersTb, IFNULL(FORMAT(((dq.enters - tb.enters)/tb.enters)*100,1),0) rateTb FROM (SELECT st.date,SUM(enters) enters,FORMAT(SUM(enters)/ca.storeNum,0) entersAvg FROM t_statistic_day st, (SELECT *,LENGTH(STOREIDS) - LENGTH(REPLACE(STOREIDS,',',''))+1 storeNum FROM t_campaigns WHERE id = 1) ca WHERE LOCATE(st.store_id,CONCAT(ca.storeids,',')) > 0 AND st.date >= DATE_FORMAT(ca.START_TIME,'%Y%m%d') AND st.date <= DATE_FORMAT(ca.END_TIME,'%Y%m%d') GROUP BY DATE) dq LEFT JOIN (SELECT st.date,SUM(enters) enters FROM t_statistic_day st, (SELECT * FROM t_campaigns WHERE id = 1) ca WHERE LOCATE(st.store_id,CONCAT(ca.storeids,',')) > 0 AND st.date >= DATE_FORMAT(ca.START_TB_TIME,'%Y%m%d') AND st.date <= DATE_FORMAT(ca.END_TB_TIME,'%Y%m%d') GROUP BY DATE) tb -- The number of days between the current date and the comparison date is a fixed value, -- 364 is the number of days between the current start time and the comparison start time ON DATEDIFF(dq.date,tb.date) = 364
5, mysql query statement similar to rownum
SELECT @rownum:=@rownum+1 rownum,s.* FROM (SELECT @rownum:=0) r,t_deal_sum s
6 Get the time difference, add a time to the time base
6.1 TIMESTAMPDIFF
grammar:
TIMESTAMPDIFF(interval,datetime_expr1,datetime_expr2)。
illustrate:
Returns the integer difference between the date or datetime expressions datetime_expr1 and datetime_expr2the. The unit of the result is given by the interval parameter. This parameter must be one of the following values:
parameter:
FRAC_SECOND means the interval is in milliseconds
SECOND seconds
MINUTE minutes
HOUR hours
DAY days
WEEK week
MONTH month
QUARTER quarter
YEAR
mysql> select TIMESTAMPDIFF(day,'2012-08-24','2012-08-30'); +----------------------------------------------+ | TIMESTAMPDIFF(day,'2012-08-24','2012-08-30') | +----------------------------------------------+ | 6 | +----------------------------------------------+ 1 row in set (0.00 sec)
6.2 TIMESTAMPADD
grammar:
TIMESTAMPADD(interval,int_expr,datetime_expr)
illustrate:
Add the integer expression int_expr to the date or datetime expression datetime_expr. The interval in the formula is the same as the value listed above.
mysql> select TIMESTAMPADD(MINUTE,8820,'2012-08-24 09:00:00'); +-------------------------------------------------+ | TIMESTAMPADD(MINUTE,8820,'2012-08-24 09:00:00') | +-------------------------------------------------+ | 2012-08-30 12:00:00 | +-------------------------------------------------+ 1 row in set (0.00 sec)
Example 1:
-- get time difference SELECT CONCAT(TIMESTAMPDIFF(DAY,'2016-09-21 10:17:57','2016-12-21 11:17:57'),'天',TIMEDIFF('11:17:57','10:17:57')) day1;Result: Example 2:
-- Convert time to days, hours, minutes SELECT CONCAT( FLOOR(HOUR(SEC_TO_TIME(TIMESTAMPDIFF(SECOND,'2016-07-21 08:46:00','2016-12-01 12:30')))/24), ' 天 ', MOD(HOUR(SEC_TO_TIME(TIMESTAMPDIFF(SECOND,'2016-07-21 08:46:00', '2016-12-01 12:30'))),24),' 时 ', MINUTE(SEC_TO_TIME(TIMESTAMPDIFF(SECOND,'2016-07-21 08:46:00', '2016-12-01 12:30'))),' 分' ) str2;result: