New to SQL. Would like to convert an IF(COUNTIFS()) Excel formula to SQL code and have SQL calculate it instead of ExcelHow to auto populate fields from an excel spreadsheet into a web databaseIdentifying IDs whose transactions satisfy a specific conditionExcel 2010 - Count Unique values only in a SUBTOTAL cellMS SQL: return HTML from SQL PIVOT RESULTS with dynamic name/number of columnsAvoid duplication of values for certain fieldsOrder, OrderItem, Product. Write Product details to OrderItem?Excel formula using countifExcel Countifs or SumProduct formulasSumproduct to be evaluated in VBA ExcelInventory recalculation given a final value

What is the English equivalent of 干物女 (dried fish woman)?

How to access mouse event coordinates? (conveniently)

Are lithium batteries allowed in the International Space Station?

Won 50K! Now what should I do with it

Should you avoid redundant information after dialogue?

When is pointing out a person's hypocrisy not considered to be a logical fallacy?

Back to the nineties!

Filtering fine silt/mud from water (not necessarily bacteria etc.)

Does Google Maps take into account hills/inclines for route times?

What's the point of this scene involving Flash Thompson at the airport?

Why hasn't the U.S. government paid war reparations to any country it attacked?

Why would guns not work in the dungeon?

Supporting developers who insist on using their pet language

Verifying Hamiltonian Cycle solution in O(n^2), n is the length of the encoding of G

Cubic programming and beyond?

Behavior of the zero and negative/sign flags on classic instruction sets

Why do they not say "The Baby"

Could the crash sites of the Apollo 11 and 16 LMs be seen by the LRO?

Align by center of symbol

Why do candidates not quit if they no longer have a realistic chance to win in the 2020 US presidents election

What does a red v with a dot above mean in the Misal rico de Cisneros (Spain, 1518)?

What caused Windows ME's terrible reputation?

School House Points (Python + SQLite)

Why can't air tickets just accept only the passport number without any names?



New to SQL. Would like to convert an IF(COUNTIFS()) Excel formula to SQL code and have SQL calculate it instead of Excel


How to auto populate fields from an excel spreadsheet into a web databaseIdentifying IDs whose transactions satisfy a specific conditionExcel 2010 - Count Unique values only in a SUBTOTAL cellMS SQL: return HTML from SQL PIVOT RESULTS with dynamic name/number of columnsAvoid duplication of values for certain fieldsOrder, OrderItem, Product. Write Product details to OrderItem?Excel formula using countifExcel Countifs or SumProduct formulasSumproduct to be evaluated in VBA ExcelInventory recalculation given a final value






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am running SQL Server 2008 R2 (RTM).



I have a SQL query that pulls Dates, Products, Customers and Units:



select 

[Transaction Date] as Date,
[SKU] as Product,
[Customer Name] as Customer,
sum(Qty) as Units

from dataset

where [Transaction Date] < '2019-03-01' and [Transaction Date] >= '2016-01-01'

group by [Transaction Date], [SKU], [Customer Name]

order by [Transaction Date]


This pulls hundreds of thousands of records and I wanted to determine if a certain transaction was a new order or reorder based on the following logic:



Reorder: That specific Customer has ordered that specific product in the last 6 months



New Order: That specific Customer hasn’t ordered that specific product in the last 6 months



For that I have this formula in Excel that seems to be working:



=IF(COUNTIFS(A$1:A1,">="&DATE(YEAR(A2),MONTH(A2)-6,DAY(A2)),C$1:C1,C2,B$1:B1,B2),"Reorder","New Order")




The formula works when I paste it individually or in a smaller dataset, but when I try to copy paste it to all 500K+ rows, Excel gives up because it loops for each calculation.



This could probably be done in SQL, but I don’t have the knowledge on how to convert this excel formula to SQL, I just started studying it.










share|improve this question
























  • And how are we supposed to know what your Excel cells contains except A2 containing a date, please add an explanation. Also add some sample data and expected output. What database are you using, please add the correct tag to your question. Lastly, is that sql query really working, a SUM() function usually requires a GROUP BY?

    – Joakim Danielson
    Mar 26 at 6:38











  • Hi Joakim. I'm sorry, this is my first time posting here. I didn't know the [where / group by/ order by] parts of my query were relevant to the question. Apart from that I don't really understand your other guidelines. Column A contains transaction dates with A1 being the header. Expected output would be for the query to check if that customer purchased that specific product in the last 6 months. If yes, then it's a reorder, if not it's a new order.

    – Deasasss
    Mar 26 at 16:11











  • It's good to minimize but not to much since it can make it unclear if you have an error in your code, about the excel code well maybe I read to much into that and it is not so relevant for the question

    – Joakim Danielson
    Mar 26 at 16:20











  • The server is Microsoft SQL Server 2008.

    – Deasasss
    Mar 26 at 16:20

















0















I am running SQL Server 2008 R2 (RTM).



I have a SQL query that pulls Dates, Products, Customers and Units:



select 

[Transaction Date] as Date,
[SKU] as Product,
[Customer Name] as Customer,
sum(Qty) as Units

from dataset

where [Transaction Date] < '2019-03-01' and [Transaction Date] >= '2016-01-01'

group by [Transaction Date], [SKU], [Customer Name]

order by [Transaction Date]


This pulls hundreds of thousands of records and I wanted to determine if a certain transaction was a new order or reorder based on the following logic:



Reorder: That specific Customer has ordered that specific product in the last 6 months



New Order: That specific Customer hasn’t ordered that specific product in the last 6 months



For that I have this formula in Excel that seems to be working:



=IF(COUNTIFS(A$1:A1,">="&DATE(YEAR(A2),MONTH(A2)-6,DAY(A2)),C$1:C1,C2,B$1:B1,B2),"Reorder","New Order")




The formula works when I paste it individually or in a smaller dataset, but when I try to copy paste it to all 500K+ rows, Excel gives up because it loops for each calculation.



This could probably be done in SQL, but I don’t have the knowledge on how to convert this excel formula to SQL, I just started studying it.










share|improve this question
























  • And how are we supposed to know what your Excel cells contains except A2 containing a date, please add an explanation. Also add some sample data and expected output. What database are you using, please add the correct tag to your question. Lastly, is that sql query really working, a SUM() function usually requires a GROUP BY?

    – Joakim Danielson
    Mar 26 at 6:38











  • Hi Joakim. I'm sorry, this is my first time posting here. I didn't know the [where / group by/ order by] parts of my query were relevant to the question. Apart from that I don't really understand your other guidelines. Column A contains transaction dates with A1 being the header. Expected output would be for the query to check if that customer purchased that specific product in the last 6 months. If yes, then it's a reorder, if not it's a new order.

    – Deasasss
    Mar 26 at 16:11











  • It's good to minimize but not to much since it can make it unclear if you have an error in your code, about the excel code well maybe I read to much into that and it is not so relevant for the question

    – Joakim Danielson
    Mar 26 at 16:20











  • The server is Microsoft SQL Server 2008.

    – Deasasss
    Mar 26 at 16:20













0












0








0








I am running SQL Server 2008 R2 (RTM).



I have a SQL query that pulls Dates, Products, Customers and Units:



select 

[Transaction Date] as Date,
[SKU] as Product,
[Customer Name] as Customer,
sum(Qty) as Units

from dataset

where [Transaction Date] < '2019-03-01' and [Transaction Date] >= '2016-01-01'

group by [Transaction Date], [SKU], [Customer Name]

order by [Transaction Date]


This pulls hundreds of thousands of records and I wanted to determine if a certain transaction was a new order or reorder based on the following logic:



Reorder: That specific Customer has ordered that specific product in the last 6 months



New Order: That specific Customer hasn’t ordered that specific product in the last 6 months



For that I have this formula in Excel that seems to be working:



=IF(COUNTIFS(A$1:A1,">="&DATE(YEAR(A2),MONTH(A2)-6,DAY(A2)),C$1:C1,C2,B$1:B1,B2),"Reorder","New Order")




The formula works when I paste it individually or in a smaller dataset, but when I try to copy paste it to all 500K+ rows, Excel gives up because it loops for each calculation.



This could probably be done in SQL, but I don’t have the knowledge on how to convert this excel formula to SQL, I just started studying it.










share|improve this question
















I am running SQL Server 2008 R2 (RTM).



I have a SQL query that pulls Dates, Products, Customers and Units:



select 

[Transaction Date] as Date,
[SKU] as Product,
[Customer Name] as Customer,
sum(Qty) as Units

from dataset

where [Transaction Date] < '2019-03-01' and [Transaction Date] >= '2016-01-01'

group by [Transaction Date], [SKU], [Customer Name]

order by [Transaction Date]


This pulls hundreds of thousands of records and I wanted to determine if a certain transaction was a new order or reorder based on the following logic:



Reorder: That specific Customer has ordered that specific product in the last 6 months



New Order: That specific Customer hasn’t ordered that specific product in the last 6 months



For that I have this formula in Excel that seems to be working:



=IF(COUNTIFS(A$1:A1,">="&DATE(YEAR(A2),MONTH(A2)-6,DAY(A2)),C$1:C1,C2,B$1:B1,B2),"Reorder","New Order")




The formula works when I paste it individually or in a smaller dataset, but when I try to copy paste it to all 500K+ rows, Excel gives up because it loops for each calculation.



This could probably be done in SQL, but I don’t have the knowledge on how to convert this excel formula to SQL, I just started studying it.







sql sql-server excel-formula sql-server-2008-r2






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 27 at 0:55









Gordon Linoff

833k38 gold badges341 silver badges447 bronze badges




833k38 gold badges341 silver badges447 bronze badges










asked Mar 26 at 6:29









DeasasssDeasasss

11 bronze badge




11 bronze badge












  • And how are we supposed to know what your Excel cells contains except A2 containing a date, please add an explanation. Also add some sample data and expected output. What database are you using, please add the correct tag to your question. Lastly, is that sql query really working, a SUM() function usually requires a GROUP BY?

    – Joakim Danielson
    Mar 26 at 6:38











  • Hi Joakim. I'm sorry, this is my first time posting here. I didn't know the [where / group by/ order by] parts of my query were relevant to the question. Apart from that I don't really understand your other guidelines. Column A contains transaction dates with A1 being the header. Expected output would be for the query to check if that customer purchased that specific product in the last 6 months. If yes, then it's a reorder, if not it's a new order.

    – Deasasss
    Mar 26 at 16:11











  • It's good to minimize but not to much since it can make it unclear if you have an error in your code, about the excel code well maybe I read to much into that and it is not so relevant for the question

    – Joakim Danielson
    Mar 26 at 16:20











  • The server is Microsoft SQL Server 2008.

    – Deasasss
    Mar 26 at 16:20

















  • And how are we supposed to know what your Excel cells contains except A2 containing a date, please add an explanation. Also add some sample data and expected output. What database are you using, please add the correct tag to your question. Lastly, is that sql query really working, a SUM() function usually requires a GROUP BY?

    – Joakim Danielson
    Mar 26 at 6:38











  • Hi Joakim. I'm sorry, this is my first time posting here. I didn't know the [where / group by/ order by] parts of my query were relevant to the question. Apart from that I don't really understand your other guidelines. Column A contains transaction dates with A1 being the header. Expected output would be for the query to check if that customer purchased that specific product in the last 6 months. If yes, then it's a reorder, if not it's a new order.

    – Deasasss
    Mar 26 at 16:11











  • It's good to minimize but not to much since it can make it unclear if you have an error in your code, about the excel code well maybe I read to much into that and it is not so relevant for the question

    – Joakim Danielson
    Mar 26 at 16:20











  • The server is Microsoft SQL Server 2008.

    – Deasasss
    Mar 26 at 16:20
















And how are we supposed to know what your Excel cells contains except A2 containing a date, please add an explanation. Also add some sample data and expected output. What database are you using, please add the correct tag to your question. Lastly, is that sql query really working, a SUM() function usually requires a GROUP BY?

– Joakim Danielson
Mar 26 at 6:38





And how are we supposed to know what your Excel cells contains except A2 containing a date, please add an explanation. Also add some sample data and expected output. What database are you using, please add the correct tag to your question. Lastly, is that sql query really working, a SUM() function usually requires a GROUP BY?

– Joakim Danielson
Mar 26 at 6:38













Hi Joakim. I'm sorry, this is my first time posting here. I didn't know the [where / group by/ order by] parts of my query were relevant to the question. Apart from that I don't really understand your other guidelines. Column A contains transaction dates with A1 being the header. Expected output would be for the query to check if that customer purchased that specific product in the last 6 months. If yes, then it's a reorder, if not it's a new order.

– Deasasss
Mar 26 at 16:11





Hi Joakim. I'm sorry, this is my first time posting here. I didn't know the [where / group by/ order by] parts of my query were relevant to the question. Apart from that I don't really understand your other guidelines. Column A contains transaction dates with A1 being the header. Expected output would be for the query to check if that customer purchased that specific product in the last 6 months. If yes, then it's a reorder, if not it's a new order.

– Deasasss
Mar 26 at 16:11













It's good to minimize but not to much since it can make it unclear if you have an error in your code, about the excel code well maybe I read to much into that and it is not so relevant for the question

– Joakim Danielson
Mar 26 at 16:20





It's good to minimize but not to much since it can make it unclear if you have an error in your code, about the excel code well maybe I read to much into that and it is not so relevant for the question

– Joakim Danielson
Mar 26 at 16:20













The server is Microsoft SQL Server 2008.

– Deasasss
Mar 26 at 16:20





The server is Microsoft SQL Server 2008.

– Deasasss
Mar 26 at 16:20












3 Answers
3






active

oldest

votes


















1














You're doing pretty well with the start of your query there. There are three additional functions you're looking to add to your query.



The first thing you'll need is the easiest. GETDATE() simply returns the current date. You'll need that when you're comparing the current date to the transaction date.



The second function is DATEDIFF, which will give you a unit of time between two dates (months, days, years, quarters, etc). Using DATEDIFF, you can say "is this date within the last 6 months". The format for this is pretty easy. It's DATEDIFF(interval, date1, date2).



The thrid function you're looking for is CASE, which allows you to tell SQL to give you one answer if one condition is met, but a different answer if a different condition is met. For your example, you can say "if the difference in days is < 60, return 'Reorder', if not give me 'New Order'".



Putting it all together:



SELECT CASE 
WHEN DATEDIFF(MONTH, [Transaction Date], GETDATE()) <= 6
THEN 'Reorder'
ELSE 'New Order'
END as ORDER_TYPE
,[Transaction Date] AS DATE
,[SKU] AS PRODUCT
,[Customer Name] AS CUSTOMER
,Qty AS UNITS
FROM DATASET


  • For additonal examples on CASE, take a look at this site: https://www.w3schools.com/sql/sql_ref_case.asp

  • For additional examples on DATEDIFF, take a look here: See the
    following webpage for examples and a chance to try it out:
    https://www.w3schools.com/sql/func_sqlserver_datediff.asp





share|improve this answer























  • Hi Moose, Thank you for your detailed answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

    – Deasasss
    Mar 26 at 16:23


















0














SELECT CASE
WHEN Datediff(day, [transaction date], Getdate()) <= 180 THEN 'reorder'
ELSE 'Neworder'
END,
[transaction date] AS Date,
[sku] AS Product,
[customer name] AS Customer,
qty AS Units
FROM datase





share|improve this answer




















  • 1





    Besides code, I think your answer should provide an explanation of what it does.

    – Edgar Ramírez Mondragón
    Mar 26 at 7:32











  • Especially if the first three words in the title of the question are "New to SQL".

    – Wai Ha Lee
    Mar 26 at 7:58











  • Hi Rocky, Thank you for your answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

    – Deasasss
    Mar 26 at 16:25


















0














If I understand correctly, you want to peak at the previous date and make a comparison. This suggests lag():



select (case when lag([Transaction Date]) over (partition by SKU, [Customer Name] order by [Transaction Date]) >
dateadd(month, -6, [Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
[Transaction Date] as Date,
[SKU] as Product,
[Customer Name] as Customer,
sum(Qty) as Units
from dataset d
group by [Transaction Date], [SKU], [Customer Name];


EDIT:



In SQL Server 2008, you can emulate the LAG() using OUTER APPLY:



select (case when dprev.[Transaction Date] >
dateadd(month, -6, d.[Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
d.[Transaction Date] as Date,
d.[SKU] as Product,
d.[Customer Name] as Customer,
sum(d.Qty) as Units
from dataset d outer apply
(select top (1) dprev.*
from dataset dprev
where dprev.SKU = d.SKU and
dprev.[Customer Name] = d.[Customer Name] and
dprev.[Transaction Date] < d.[Transaction Date]
order by dprev.[Transaction Date] desc
) dprev
group by d.[Transaction Date], d.[SKU], d.[Customer Name];





share|improve this answer

























  • Hi Gordon. Thank you for your input! As I mentioned I'm still new to SQL and didn't know that I had to post the SQL server into my question as well. I tried running the lag function and it said 'lag' is not a recognized built-in function name. After that I checked and saw that lag only works 2012 and onwards, and my server is 2008.

    – Deasasss
    Mar 26 at 16:25













Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55351015%2fnew-to-sql-would-like-to-convert-an-ifcountifs-excel-formula-to-sql-code-an%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














You're doing pretty well with the start of your query there. There are three additional functions you're looking to add to your query.



The first thing you'll need is the easiest. GETDATE() simply returns the current date. You'll need that when you're comparing the current date to the transaction date.



The second function is DATEDIFF, which will give you a unit of time between two dates (months, days, years, quarters, etc). Using DATEDIFF, you can say "is this date within the last 6 months". The format for this is pretty easy. It's DATEDIFF(interval, date1, date2).



The thrid function you're looking for is CASE, which allows you to tell SQL to give you one answer if one condition is met, but a different answer if a different condition is met. For your example, you can say "if the difference in days is < 60, return 'Reorder', if not give me 'New Order'".



Putting it all together:



SELECT CASE 
WHEN DATEDIFF(MONTH, [Transaction Date], GETDATE()) <= 6
THEN 'Reorder'
ELSE 'New Order'
END as ORDER_TYPE
,[Transaction Date] AS DATE
,[SKU] AS PRODUCT
,[Customer Name] AS CUSTOMER
,Qty AS UNITS
FROM DATASET


  • For additonal examples on CASE, take a look at this site: https://www.w3schools.com/sql/sql_ref_case.asp

  • For additional examples on DATEDIFF, take a look here: See the
    following webpage for examples and a chance to try it out:
    https://www.w3schools.com/sql/func_sqlserver_datediff.asp





share|improve this answer























  • Hi Moose, Thank you for your detailed answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

    – Deasasss
    Mar 26 at 16:23















1














You're doing pretty well with the start of your query there. There are three additional functions you're looking to add to your query.



The first thing you'll need is the easiest. GETDATE() simply returns the current date. You'll need that when you're comparing the current date to the transaction date.



The second function is DATEDIFF, which will give you a unit of time between two dates (months, days, years, quarters, etc). Using DATEDIFF, you can say "is this date within the last 6 months". The format for this is pretty easy. It's DATEDIFF(interval, date1, date2).



The thrid function you're looking for is CASE, which allows you to tell SQL to give you one answer if one condition is met, but a different answer if a different condition is met. For your example, you can say "if the difference in days is < 60, return 'Reorder', if not give me 'New Order'".



Putting it all together:



SELECT CASE 
WHEN DATEDIFF(MONTH, [Transaction Date], GETDATE()) <= 6
THEN 'Reorder'
ELSE 'New Order'
END as ORDER_TYPE
,[Transaction Date] AS DATE
,[SKU] AS PRODUCT
,[Customer Name] AS CUSTOMER
,Qty AS UNITS
FROM DATASET


  • For additonal examples on CASE, take a look at this site: https://www.w3schools.com/sql/sql_ref_case.asp

  • For additional examples on DATEDIFF, take a look here: See the
    following webpage for examples and a chance to try it out:
    https://www.w3schools.com/sql/func_sqlserver_datediff.asp





share|improve this answer























  • Hi Moose, Thank you for your detailed answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

    – Deasasss
    Mar 26 at 16:23













1












1








1







You're doing pretty well with the start of your query there. There are three additional functions you're looking to add to your query.



The first thing you'll need is the easiest. GETDATE() simply returns the current date. You'll need that when you're comparing the current date to the transaction date.



The second function is DATEDIFF, which will give you a unit of time between two dates (months, days, years, quarters, etc). Using DATEDIFF, you can say "is this date within the last 6 months". The format for this is pretty easy. It's DATEDIFF(interval, date1, date2).



The thrid function you're looking for is CASE, which allows you to tell SQL to give you one answer if one condition is met, but a different answer if a different condition is met. For your example, you can say "if the difference in days is < 60, return 'Reorder', if not give me 'New Order'".



Putting it all together:



SELECT CASE 
WHEN DATEDIFF(MONTH, [Transaction Date], GETDATE()) <= 6
THEN 'Reorder'
ELSE 'New Order'
END as ORDER_TYPE
,[Transaction Date] AS DATE
,[SKU] AS PRODUCT
,[Customer Name] AS CUSTOMER
,Qty AS UNITS
FROM DATASET


  • For additonal examples on CASE, take a look at this site: https://www.w3schools.com/sql/sql_ref_case.asp

  • For additional examples on DATEDIFF, take a look here: See the
    following webpage for examples and a chance to try it out:
    https://www.w3schools.com/sql/func_sqlserver_datediff.asp





share|improve this answer













You're doing pretty well with the start of your query there. There are three additional functions you're looking to add to your query.



The first thing you'll need is the easiest. GETDATE() simply returns the current date. You'll need that when you're comparing the current date to the transaction date.



The second function is DATEDIFF, which will give you a unit of time between two dates (months, days, years, quarters, etc). Using DATEDIFF, you can say "is this date within the last 6 months". The format for this is pretty easy. It's DATEDIFF(interval, date1, date2).



The thrid function you're looking for is CASE, which allows you to tell SQL to give you one answer if one condition is met, but a different answer if a different condition is met. For your example, you can say "if the difference in days is < 60, return 'Reorder', if not give me 'New Order'".



Putting it all together:



SELECT CASE 
WHEN DATEDIFF(MONTH, [Transaction Date], GETDATE()) <= 6
THEN 'Reorder'
ELSE 'New Order'
END as ORDER_TYPE
,[Transaction Date] AS DATE
,[SKU] AS PRODUCT
,[Customer Name] AS CUSTOMER
,Qty AS UNITS
FROM DATASET


  • For additonal examples on CASE, take a look at this site: https://www.w3schools.com/sql/sql_ref_case.asp

  • For additional examples on DATEDIFF, take a look here: See the
    following webpage for examples and a chance to try it out:
    https://www.w3schools.com/sql/func_sqlserver_datediff.asp






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 26 at 7:56









MooseMoose

1709 bronze badges




1709 bronze badges












  • Hi Moose, Thank you for your detailed answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

    – Deasasss
    Mar 26 at 16:23

















  • Hi Moose, Thank you for your detailed answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

    – Deasasss
    Mar 26 at 16:23
















Hi Moose, Thank you for your detailed answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

– Deasasss
Mar 26 at 16:23





Hi Moose, Thank you for your detailed answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

– Deasasss
Mar 26 at 16:23













0














SELECT CASE
WHEN Datediff(day, [transaction date], Getdate()) <= 180 THEN 'reorder'
ELSE 'Neworder'
END,
[transaction date] AS Date,
[sku] AS Product,
[customer name] AS Customer,
qty AS Units
FROM datase





share|improve this answer




















  • 1





    Besides code, I think your answer should provide an explanation of what it does.

    – Edgar Ramírez Mondragón
    Mar 26 at 7:32











  • Especially if the first three words in the title of the question are "New to SQL".

    – Wai Ha Lee
    Mar 26 at 7:58











  • Hi Rocky, Thank you for your answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

    – Deasasss
    Mar 26 at 16:25















0














SELECT CASE
WHEN Datediff(day, [transaction date], Getdate()) <= 180 THEN 'reorder'
ELSE 'Neworder'
END,
[transaction date] AS Date,
[sku] AS Product,
[customer name] AS Customer,
qty AS Units
FROM datase





share|improve this answer




















  • 1





    Besides code, I think your answer should provide an explanation of what it does.

    – Edgar Ramírez Mondragón
    Mar 26 at 7:32











  • Especially if the first three words in the title of the question are "New to SQL".

    – Wai Ha Lee
    Mar 26 at 7:58











  • Hi Rocky, Thank you for your answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

    – Deasasss
    Mar 26 at 16:25













0












0








0







SELECT CASE
WHEN Datediff(day, [transaction date], Getdate()) <= 180 THEN 'reorder'
ELSE 'Neworder'
END,
[transaction date] AS Date,
[sku] AS Product,
[customer name] AS Customer,
qty AS Units
FROM datase





share|improve this answer















SELECT CASE
WHEN Datediff(day, [transaction date], Getdate()) <= 180 THEN 'reorder'
ELSE 'Neworder'
END,
[transaction date] AS Date,
[sku] AS Product,
[customer name] AS Customer,
qty AS Units
FROM datase






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 26 at 8:01









karel

2,4839 gold badges29 silver badges32 bronze badges




2,4839 gold badges29 silver badges32 bronze badges










answered Mar 26 at 7:27









RockyRocky

1




1







  • 1





    Besides code, I think your answer should provide an explanation of what it does.

    – Edgar Ramírez Mondragón
    Mar 26 at 7:32











  • Especially if the first three words in the title of the question are "New to SQL".

    – Wai Ha Lee
    Mar 26 at 7:58











  • Hi Rocky, Thank you for your answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

    – Deasasss
    Mar 26 at 16:25












  • 1





    Besides code, I think your answer should provide an explanation of what it does.

    – Edgar Ramírez Mondragón
    Mar 26 at 7:32











  • Especially if the first three words in the title of the question are "New to SQL".

    – Wai Ha Lee
    Mar 26 at 7:58











  • Hi Rocky, Thank you for your answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

    – Deasasss
    Mar 26 at 16:25







1




1





Besides code, I think your answer should provide an explanation of what it does.

– Edgar Ramírez Mondragón
Mar 26 at 7:32





Besides code, I think your answer should provide an explanation of what it does.

– Edgar Ramírez Mondragón
Mar 26 at 7:32













Especially if the first three words in the title of the question are "New to SQL".

– Wai Ha Lee
Mar 26 at 7:58





Especially if the first three words in the title of the question are "New to SQL".

– Wai Ha Lee
Mar 26 at 7:58













Hi Rocky, Thank you for your answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

– Deasasss
Mar 26 at 16:25





Hi Rocky, Thank you for your answer! This does not have the desired output, it shows transactions up until a certain date to be all new orders and then every transaction is a reorder. What I would like is for the script to check if that specific customer purchased that specific product in the last 6 months and if the customer did, then it would be a reorder, if it did not, then it would be a new order.

– Deasasss
Mar 26 at 16:25











0














If I understand correctly, you want to peak at the previous date and make a comparison. This suggests lag():



select (case when lag([Transaction Date]) over (partition by SKU, [Customer Name] order by [Transaction Date]) >
dateadd(month, -6, [Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
[Transaction Date] as Date,
[SKU] as Product,
[Customer Name] as Customer,
sum(Qty) as Units
from dataset d
group by [Transaction Date], [SKU], [Customer Name];


EDIT:



In SQL Server 2008, you can emulate the LAG() using OUTER APPLY:



select (case when dprev.[Transaction Date] >
dateadd(month, -6, d.[Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
d.[Transaction Date] as Date,
d.[SKU] as Product,
d.[Customer Name] as Customer,
sum(d.Qty) as Units
from dataset d outer apply
(select top (1) dprev.*
from dataset dprev
where dprev.SKU = d.SKU and
dprev.[Customer Name] = d.[Customer Name] and
dprev.[Transaction Date] < d.[Transaction Date]
order by dprev.[Transaction Date] desc
) dprev
group by d.[Transaction Date], d.[SKU], d.[Customer Name];





share|improve this answer

























  • Hi Gordon. Thank you for your input! As I mentioned I'm still new to SQL and didn't know that I had to post the SQL server into my question as well. I tried running the lag function and it said 'lag' is not a recognized built-in function name. After that I checked and saw that lag only works 2012 and onwards, and my server is 2008.

    – Deasasss
    Mar 26 at 16:25















0














If I understand correctly, you want to peak at the previous date and make a comparison. This suggests lag():



select (case when lag([Transaction Date]) over (partition by SKU, [Customer Name] order by [Transaction Date]) >
dateadd(month, -6, [Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
[Transaction Date] as Date,
[SKU] as Product,
[Customer Name] as Customer,
sum(Qty) as Units
from dataset d
group by [Transaction Date], [SKU], [Customer Name];


EDIT:



In SQL Server 2008, you can emulate the LAG() using OUTER APPLY:



select (case when dprev.[Transaction Date] >
dateadd(month, -6, d.[Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
d.[Transaction Date] as Date,
d.[SKU] as Product,
d.[Customer Name] as Customer,
sum(d.Qty) as Units
from dataset d outer apply
(select top (1) dprev.*
from dataset dprev
where dprev.SKU = d.SKU and
dprev.[Customer Name] = d.[Customer Name] and
dprev.[Transaction Date] < d.[Transaction Date]
order by dprev.[Transaction Date] desc
) dprev
group by d.[Transaction Date], d.[SKU], d.[Customer Name];





share|improve this answer

























  • Hi Gordon. Thank you for your input! As I mentioned I'm still new to SQL and didn't know that I had to post the SQL server into my question as well. I tried running the lag function and it said 'lag' is not a recognized built-in function name. After that I checked and saw that lag only works 2012 and onwards, and my server is 2008.

    – Deasasss
    Mar 26 at 16:25













0












0








0







If I understand correctly, you want to peak at the previous date and make a comparison. This suggests lag():



select (case when lag([Transaction Date]) over (partition by SKU, [Customer Name] order by [Transaction Date]) >
dateadd(month, -6, [Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
[Transaction Date] as Date,
[SKU] as Product,
[Customer Name] as Customer,
sum(Qty) as Units
from dataset d
group by [Transaction Date], [SKU], [Customer Name];


EDIT:



In SQL Server 2008, you can emulate the LAG() using OUTER APPLY:



select (case when dprev.[Transaction Date] >
dateadd(month, -6, d.[Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
d.[Transaction Date] as Date,
d.[SKU] as Product,
d.[Customer Name] as Customer,
sum(d.Qty) as Units
from dataset d outer apply
(select top (1) dprev.*
from dataset dprev
where dprev.SKU = d.SKU and
dprev.[Customer Name] = d.[Customer Name] and
dprev.[Transaction Date] < d.[Transaction Date]
order by dprev.[Transaction Date] desc
) dprev
group by d.[Transaction Date], d.[SKU], d.[Customer Name];





share|improve this answer















If I understand correctly, you want to peak at the previous date and make a comparison. This suggests lag():



select (case when lag([Transaction Date]) over (partition by SKU, [Customer Name] order by [Transaction Date]) >
dateadd(month, -6, [Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
[Transaction Date] as Date,
[SKU] as Product,
[Customer Name] as Customer,
sum(Qty) as Units
from dataset d
group by [Transaction Date], [SKU], [Customer Name];


EDIT:



In SQL Server 2008, you can emulate the LAG() using OUTER APPLY:



select (case when dprev.[Transaction Date] >
dateadd(month, -6, d.[Transaction Date])
then 'Reorder'
else 'New Order'
end) as Order_Type
d.[Transaction Date] as Date,
d.[SKU] as Product,
d.[Customer Name] as Customer,
sum(d.Qty) as Units
from dataset d outer apply
(select top (1) dprev.*
from dataset dprev
where dprev.SKU = d.SKU and
dprev.[Customer Name] = d.[Customer Name] and
dprev.[Transaction Date] < d.[Transaction Date]
order by dprev.[Transaction Date] desc
) dprev
group by d.[Transaction Date], d.[SKU], d.[Customer Name];






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 27 at 0:58

























answered Mar 26 at 11:25









Gordon LinoffGordon Linoff

833k38 gold badges341 silver badges447 bronze badges




833k38 gold badges341 silver badges447 bronze badges












  • Hi Gordon. Thank you for your input! As I mentioned I'm still new to SQL and didn't know that I had to post the SQL server into my question as well. I tried running the lag function and it said 'lag' is not a recognized built-in function name. After that I checked and saw that lag only works 2012 and onwards, and my server is 2008.

    – Deasasss
    Mar 26 at 16:25

















  • Hi Gordon. Thank you for your input! As I mentioned I'm still new to SQL and didn't know that I had to post the SQL server into my question as well. I tried running the lag function and it said 'lag' is not a recognized built-in function name. After that I checked and saw that lag only works 2012 and onwards, and my server is 2008.

    – Deasasss
    Mar 26 at 16:25
















Hi Gordon. Thank you for your input! As I mentioned I'm still new to SQL and didn't know that I had to post the SQL server into my question as well. I tried running the lag function and it said 'lag' is not a recognized built-in function name. After that I checked and saw that lag only works 2012 and onwards, and my server is 2008.

– Deasasss
Mar 26 at 16:25





Hi Gordon. Thank you for your input! As I mentioned I'm still new to SQL and didn't know that I had to post the SQL server into my question as well. I tried running the lag function and it said 'lag' is not a recognized built-in function name. After that I checked and saw that lag only works 2012 and onwards, and my server is 2008.

– Deasasss
Mar 26 at 16:25

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55351015%2fnew-to-sql-would-like-to-convert-an-ifcountifs-excel-formula-to-sql-code-an%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해