Auto-generate custom ID using mysql workbench? - mysql

I want it to be in the format of "YYYY-###" where it gives the year and number ### incriminating starting from 1. ex: 2016-001, 2016-002, 2016-003,...

You can use a Numbers/Tally table if you like. I use a UDF to dynamically generate number ranges. As you can see in the function call I set the range from 1 to 12 with an increment of 1
Declare #Table table (SomeField int)
Insert into #Table values
(2015),(2016)
Select StringValue =cast(SomeField as varchar(25))+'-'+right('000'+cast(RetVal as varchar(25)),3)
,SomeField
,RetVal
From #Table A
Join (Select RetVal=cast(RetVal as int) from [dbo].[udf-Create-Range-Number](1,12,1)) B
on (1=1)
Returns
StringValue SomeField RetVal
2015-001 2015 1
2015-002 2015 2
2015-003 2015 3
2015-004 2015 4
2015-005 2015 5
2015-006 2015 6
2015-007 2015 7
2015-008 2015 8
2015-009 2015 9
2015-010 2015 10
2015-011 2015 11
2015-012 2015 12
2016-001 2016 1
2016-002 2016 2
2016-003 2016 3
2016-004 2016 4
2016-005 2016 5
2016-006 2016 6
2016-007 2016 7
2016-008 2016 8
2016-009 2016 9
2016-010 2016 10
2016-011 2016 11
2016-012 2016 12
The UDF
CREATE FUNCTION [dbo].[udf-Create-Range-Number] (#R1 money,#R2 money,#Incr money)
-- Syntax Select * from [dbo].[udf-Create-Range-Number](0,100,2)
Returns
#ReturnVal Table (RetVal money)
As
Begin
With NumbTable as (
Select NumbFrom = #R1
union all
Select nf.NumbFrom + #Incr
From NumbTable nf
Where nf.NumbFrom < #R2
)
Insert into #ReturnVal(RetVal)
Select NumbFrom from NumbTable Option (maxrecursion 0)
Return
End

Related

Laravel Query get row based on 2 dependent column

Help me to query this.
I have a Laravel app where have a table that has 3 columns (quartal, year, value).
quartal
year
value
1
2019
3
2
2019
5
3
2019
5
4
2019
10
1
2020
7
2
2020
5
For example, I want to get the value from quartal 3 years 2019 to quartal 2 years 2020
how to make the query for this case?
for the year I can use between but for the quartal, It depends on the year.
here is my current query. but it does not work really well
DB::table($table)
->whereBetween('year',[$startYear, $endYear])
->whereBetween('quartal',[$startQuartal, $endQuartal])
->get();
What you need to do is you need to create a compound column from quartal and year and then query that.
DB::table($table)
->whereRaw("concat(year,quartal) >= ?", "$startYear$startQuartal")
->whereRaw("concat(year,quartal) <= ?", "$endYear$endQuartal")
->get();
You can refer this for the SQL query https://www.db-fiddle.com/f/4GRH5RKqQi2Fc6wVvxK8C2/0
you can do it with filter function also and it an easy way just like
$startYear = 2019
$endyear = 2020
$startQuartar = 3
$endQuartar = 2
DB::table($table)
->whereBetween('year',[$startYear, $endYear])
->get()->filter(function($query) use
($startYear,$endYear,$startQuartar,$endQuartar){
if($query->year == $startYear and $query->quartar < $startQuartar){
return false;
}
if($query->year == $endYear and $query->quartar > $endQuartar){
return false;
}
return true;
});
How about adding the quartal to the year?
DB::table($table)
->whereBetween(
DB::raw('year + (quartal - 1) / 4'),
[
$startYear + ($startQuartal - 1) / 4,
$endYear + ($endQuartal - 1) / 4
]
)
->get();

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

Adding values from 2 rows based on conditions

I have a table as Below....
ROW gvkey datadate CQTR CYEARQ Value
1 6066 3/31/2015 0:00 1 2015 3610
2 6066 12/31/2014 0:00 4 2014 16868
3 6066 9/30/2014 0:00 3 2014 10809
4 6066 6/30/2014 0:00 2 2014 6905
5 6066 3/31/2014 0:00 1 2014 3326
I want to get the sum of Value of 3/31/2015 and 12/31/2014. Please suggest how Can I do it in MS Sql.
Are you looking for this :-
Set Nocount On;
If Object_Id('tempdb.dbo.#table') Is Not Null
Begin
Drop Table #table;
End
Create Table #table
(
Id Int Primary Key
,Col1 Int
,RDate Datetime
,Col2 Int
,RYear Int
,Col3 Int
)
Insert Into #table Values
(1,6066,'03/31/2015 0:00',1,2015,3610)
,(2,6066,'12/31/2014 0:00',4,2014,16868)
,(3,6066,'09/30/2014 0:00',3,2014,10809)
,(4,6066,'06/30/2014 0:00',2,2014,6905)
,(5,6066,'03/31/2014 0:00',1,2014,3326)
Select t.Col1
,Sum(t.Col3) As ColSum
From #table As t With (Nolock)
Where t.RDate In ('03/31/2015','12/31/2014')
Group By t.Col1

How to Display 4week per month with condition in sql

I have this logic but I cant figure out what to do to come up with the results. I want to achieve the results below, the idea is (Ex. month of October 2014), normally it has 5 weeks. If there is a 5th week and days is greater than 3 then consider whole week in the next month else add it to 4th week.
Input:
date range
from: 10-01-2014
to: 11-30-2014
Sample Output:
Date Customer week# Dates covered
10-01-2014 Cust01 1 Oct 01 - Oct 11, 2014
10-08-2014 Cust02 1 Oct 01 - Oct 11, 2014
10-17-2014 Cust02 2 Oct 12 - Oct 18, 2014
10-25-2014 Cust03 3 Oct 19 - Oct 25, 2014
10-31-2014 Cust01 4 Oct 26 - Oct 31, 2014
11-01-2014 Cust01 1 Nov 01 - Nov 08, 2014
11-28-2014 Cust02 4 Nov 23 - Nov 30, 2014
11-30-2014 Cust05 4 Nov 23 - Nov 30, 2014
Thanks
Use datepart(ww,[date]) to get week number in a year, then compare the week number by the begin date of a month.
Below is the detail approach to calculate for one date:
declare #dt date, #month_begin date, #month_end date, #week_of_month int
set #dt='20141031'
set #month_begin = convert(date,(convert(char(6),#dt,112)+'01'))
set #month_end = dateadd(day, -1, dateadd(month,1,#month_begin))
set #week_of_month = datepart(ww,#dt) - datepart(ww,convert(date,(convert(char(6),#dt,112)+'01'))) + 1
select
case when #week_of_month > 4 and datepart(dw,#month_end)>3
then 1
else #week_of_month
end as week,
case when #week_of_month > 4 and datepart(dw,#month_end)>3
then datepart(month,dateadd(month,1,#dt))
else datepart(month,#dt)
end as month

Another Pivot with Dynamic Fields

I have a view defined as follows:
Select IdSezioneDonatore, NumeroDonatore, Anno, DonaAnno
From dbo.DonazioniAnnue
Where (Anno>= YEAR(GETDATE())-4)
I will return the following fields and values:
IdSezioneDonatore NumeroDonatore Anno DonaAnno
2850 3624 2009 3
2850 5585 2009 1
2850 3624 2010 2
2850 5586 2010 1
2850 3624 2011 1
2850 5586 2011 1
.... ..... .... ...
How can I do to get a result like this?:
IdSezioneDonatore NumeroDonatore Anno 2009 Anno2010 Anno 2011 Anno 2012 Anno 2013
2850 3624 3 2 0 0 0
2850 5585 1 0 0 0 1
2850 5586 0 1 1 0 1
.... ..... ... ... ... ... ...
Tank far all
DECLARE #QUERY NVARCHAR(MAX)
DECLARE #Annos TABLE(Anno INT)
INSERT INTO #Annos
SELECT DISTINCT Anno FROM TEST
DECLARE #Annuals VARCHAR(MAX)
DECLARE #Annuals_New VARCHAR(MAX)
SELECT #Annuals = COALESCE(+#Annuals+'],[' ,'[') +CONVERT(VARCHAR(10),A.Anno)
FROM #Annos A
SET #Annuals_New = #Annuals+']'
SELECT #QUERY='SELECT * FROM TEST PIVOT (MAX(DonaAnno) FOR Anno IN ('+#Annuals_New+'))AS [pivot]'
EXEC SP_EXECUTESQL #QUERY
This would help. ;-)