SQL Server 2014 Management Studio - sql-server

I'm a non profit lawyer trying to set up a SQL Server database for my agency. The issue I'm having is query based: I need a simple query that will aggregate the total number of rows on a table, not the sum of the cell contents.
I working with 4 columns of I to: attorney's name, client name, trial date and remedy (the last 2 are date and dollar amount, so integers].
*** Script for SelectTopNRows command from SSMS***
SELECT TOP 100
[attorney]
,[client]
,[trial_date]
,[remedy]
FROM [MyLegalDB]
WHERE [trial_date] between '20160101' and '20160531'
I'm trying to find a way (script, batch file, etc) that will populate a total number of cases by month (according to trial date) total number of clients, and sum the remedy column.
Sorry for the vagueness. There are privilege rules in place. Hope that helps clarify.
Thanks

Assuming that your case history spans years, not just months, try this:
SELECT
,YEAR([trial_date]) AS [Year]
,MONTH([trial_date]) AS [Month]
,COUNT(1) AS [Trial_Count]
FROM [MyLegalDB]
WHERE [trial_date] between '20160101' and '20160531'
GROUP BY YEAR([trial_date]), MONTH([trial_date])
If you want to separate this by attorney, you would need to add that column to the SELECT list, as well as the GROUP BY clause, as such:
SELECT
[attorney]
,YEAR([trial_date]) AS [Year]
,MONTH([trial_date]) AS [Month]
,COUNT(1) AS [Trial_Count]
FROM [MyLegalDB]
WHERE [trial_date] between '20160101' and '20160531'
GROUP BY [attorney], YEAR([trial_date]), MONTH([trial_date])
This is a very general answer to a very general question. If you want me to be more specific, I'm going to have to understand your goal a little better. Hope it helps.

Related

How do I create a pivot/crosstab query in SQL Server when I don't know the column names in advance?

I am querying some sales figures in SQL Server to determine sales by customer by year. This is easy in Access:
TRANSFORM Sum(dbo_HISTORY.NET_SALES) AS SumOfNET_SALES
SELECT dbo_HISTORY.CUSTOMER_NAME
FROM dbo_HISTORY
GROUP BY dbo_HISTORY.CUSTOMER_NAME
PIVOT dbo_HISTORY.YEAR;
In SQL Server, I can add things easily enough:
SELECT [SPEC_MIS].DBO.HISTORY.CUSTOMER_NAME,[SPEC_MIS].DBO.HISTORY.YEAR,sum([SPEC_MIS].DBO.HISTORY.NET_SALES) AS SALES
FROM [SPEC_MIS].DBO.HISTORY
GROUP BY CUSTOMER_NAME,YEAR
ORDER BY CUSTOMER_NAME,YEAR
But I can't work out how to get the pivot to work. Note that I need this query to work on any arrangement of years, I don't want to have to rewrite this query every year.

Inner join query logic

I am using Sql Server Management studio.
I have the following table.
when i run the following query I get the running total for sales column
select s1.date,
sum(s2.sales)
from sales s1
join sales s2 on s1.date>=s2.date
group by s1.date;
but when i substitute s2.sales with s1.sales in the select
select s1.date,
**sum(s1.sales)**
from sales s1
join sales s2 on s1.date>=s2.date
group by s1.date;
it gives me a different answer can someone help me understand why i am facing this? since the sales column value should be the same.
The first version of your running total query is summing sales, for each dates, over dates which are strictly less than or equal to the date in each record. When you change s2.sales to s1.sales, you are then summing the current record's sales N number of times, where N is the number of records having an earlier date. This clearly is not the logic you want, so stick with the first version.
By the way, if you're using MySQL 8+, then analytic functions simplify things even further:
SELECT Date, Sales, SUM(Sales) OVER (ORDER BY Date) RunningSales
FROM sales
ORDER BY Date;

Splitting business date into Day Month and year into separate columns

My business intelligence tool is creating a lot of issues with calculating a variance YOY, instead, I am contemplating creating a view in my Database which will allow me to subtract two columns giving me the variance.
I am trying to wrap my head around the best way to go about this, been testing datepart, convert, cast on the date but I am sure I am going the wrong way about this.
select top 1
Business_date,
CONCAT(DATEPART(MM, Business_Date),'-', DATEPART(DD, Business_Date)) as
DayMonth,
case
when DATEPART(YYYY, Business_Date) = '2019' then 2019
end
from Occupancy_Forecast;
I know the code above does not give me anything where i need to be as I am trying to see the best way to do this, what I am looking for is something like the attached screenshot:
I have also included a screenshot of the current table I am reading from so you understand the current format
Using #Larnu statement regarding the pivot I have been able to create a view stored containing the data required using the below to give me the desired output:
select Resort as Resort, Business_Date as Date, [2016], [2017], [2018], [2019],
[2020]
from
(select Resort, business_date, DATEPART(YYYY, Business_Date) as Year, ADR
from Occupancy_Forecast
where Business_Date > '2015-12-31') as SourceTable
PIVOT
(
AVG(ADR)
FOR YEAR IN ([2016], [2017], [2018], [2019], [2020] )
) as PivotTable

SQL Error message: Column XXX is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

SELECT
t.[Week], MAX(t.Revenue) AS 'Max Revenue'
FROM
(SELECT
[Week], SUM([Service Total]) AS Revenue
FROM
dbo.['Data - 2017 Appmt Time$']
GROUP BY
[Week]) t;
Error:
Column 't.Week' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
What I'm trying to do is to get the max revenue and the respective week for which is that max revenue. How to make that code working? The code is working if I don't select t.[Week] in the beginning but then I get only the max revenue. If I include t.[Week] in a group by clause, as the message suggests, that I have a list of all revenues week-by-week, but I don't need it. I only need the max revenue and for which week it is.
Apologies if my question is stupid, I'm a beginner in SQL and already lost much time searching for a solution. :( Thanks a lot in advance!
You cannot use a non aggregate column in select which is not part of Group By.
Actually you don't need derived table for this, to find the week with maximum revenue use TOP 1 with Order by
SELECT top 1 [Week],
Revenue = SUM([Service Total])
FROM dbo.['Data - 2017 Appmt Time$']
GROUP BY [Week]
order by Revenue desc
As mentioned by Dan Guzman, if there is a tie in maximum revenue and you want all the tie records then replace TOP 1 with TOP 1 with Ties

Querying a table with a date/time filter in SQL Server 2008

I have a table in my database. This table is called Order. It has a structure like this
ID
CustomerID
OrderDate
Quantity
Price
I need to get all of the orders for the past 2 weeks. How do I do that? I don't understand how to work with dates in this manner in SQL.
Thank you!
You could incorporate something like this into your WHERE clause:
WHERE OrderDate >= DATEADD(day,-14,GetDate())
(i.e OrderDate is more recent than today minus 14 days.)
[I don't have access to SQL Server here so I can't check it - but it might work :)]
Edit: Depending on the exact datatype of OrderDate, I'm not sure what will happen in cases where you have e.g. an order half way through the day two weeks ago, so you might want to check what happens.
marnir answer is the way to do it but this is another option excluding OrderDate > today:
select * from Order
where [OrderDate]
BETWEEN DATEADD(dd, -14, GetDate()) AND GetDate()
Here is another possible way of retrieving orders placed in the last 2 weeks. This is assuming that OrderDate is a column of data type datetime. Screenshot #1 shows sample data in a table named dbo.[Order] similar to your requirements and output of below query against that table data. This query was tested in SQL Server 2008 R2 but is compatible with other SQL Server versions as well.
SELECT Id
, CustomerId
, OrderDate
, Quantity
, Price
FROM dbo.[Order]
WHERE DATEDIFF(WEEK, OrderDate, GETDATE()) <= 2
Hope that helps.
Screenshot #1

Resources