SQL Table UPDATE by row with days per month - sql

SQL Server 2005:
I'm attempting to create a table that looks like this:
JAN | FEB | March .......Dec | YTD
Total Volume:
Days in Month:
Gallons per day AVG:
Three rows with description on left, 13 columns (one for each month and year to date total).
I know how to populate the total volume per month. What would I use for days per month and average? I'd like the days per month to show either the complete number of days if it is a past month or current completed days if its the current month.

You are pivoting the data, so you want the results in columns. You can do this by using direct calculation. Here is an example for the first three months:
select 'Days In Month' as col1,
(case when month(getdate()) < 1 then 0
when month(getdate()) = 1 then day(getdate())
else 31
end) as Jan,
(case when month(getdate()) < 2 then 0
when month(getdate()) = 2 then day(getdate())
when year(getdate()) % 4 = 0 then 29
else 28
end) as Feb,
(case when month(getdate()) < 3 then 0
when month(getdate()) = 3 then day(getdate())
else 31
end) as Mar,

Related

How to get data from date

Hi I would like to get data from date for users. I ve got a table with all months but i would like to get how much they earn on month
user
month
money
1
january
10
2
january
1
1
april
100
2
april
1000
1
march
0
2
march
1
And result should be:
user
money_on_april
money_on_march
1
100
0
2
1000
1
3
0
0
Assuming you want a column for every month, or a certain subset of months:
SELECT
user,
SUM(CASE month WHEN 'january' THEN money ELSE 0 END) As money_on_january,
SUM(CASE month WHEN 'february' THEN money ELSE 0 END) As money_on_february,
...
FROM
YourTable
GROUP BY
user
If you only want columns for the months which exist in the table, then you'll need to use dynamic SQL instead.
If you are using MS SQL, Try PIVOT
SELECT * FROM [Your Table]
PIVOT(
SUM([money])
FOR [month] IN ([january],[april],[march])
)pvt

Group by week using SQL Server 2008

I have a table and I want to display the data by week in columns. I have done for a week but cannot do to a all weeks in a month.
In my table I want to group the data by id per week and sum it
My sample data is here: SqlFiddle
Sample o/p
121212 1212 7646 45647
Check this
SELECT month
,SUM(CASE WHEN day between 1 and 7 then Value END) as WEEK_1_VAL
,SUM(CASE WHEN day between 8 and 14 then Value END) as WEEK_2_VAL
,SUM(CASE WHEN day between 15 and 21 then Value END) as WEEK_3_VAL
,SUM(CASE WHEN day between 22 and 28 then Value END) as WEEK_4_VAL
,SUM(CASE WHEN day between 29 and 31 then Value END) as WEEK_5_VAL
FROM sample GROUP BY month
;
Output
month WEEK_1_VAL WEEK_2_VAL WEEK_3_VAL WEEK_4_VAL WEEK_5_VAL
12 8 13 1 119.78 11.89
Do a query where you group by DATEPART(week, ...), which would produce one row per week, and then PIVOT that query to make the rows into columns.

How to maintain a running balance in a month wise report

SELECT *
FROM
(SELECT
YEAR (DateOfTransaction) AS year,
LEFT(DATENAME(MONTH, DateOfTransaction), 3) AS month,
SUM(CASE WHEN TransTypeName LIKE 'credit%' THEN amount ELSE 0 END) -
SUM(CASE WHEN TransTypeName LIKE 'Debit%' THEN amount ELSE 0 END) AS Balance
FROM
.............) AS t
PIVOT (SUM(balance) FOR month IN (jan, feb, march, ...., Dec)) AS pvt
This query returns a month-wise report account balance. I want a result is running balance.
Example:
January month I credit 5000, February month I credit 2000
My query result is
year jan feb march...dec
2014 5000 2000 null ..null
I want a result like this:
year jan feb march...dec
2014 5000 7000 null ..null
(5000+2000)
Try this
SELECT year,Jan = Jan, Feb = isnull(Jan,0)+isnull(Feb,0),....
FROM
(SELECT
YEAR (DateOfTransaction) AS year,
LEFT(DATENAME(MONTH, DateOfTransaction), 3) AS month,
SUM(CASE WHEN TransTypeName LIKE 'credit%' THEN amount ELSE 0 END) -
SUM(CASE WHEN TransTypeName LIKE 'Debit%' THEN amount ELSE 0 END) AS Balance
FROM
.............) AS t
PIVOT (SUM(balance) FOR month IN (jan, feb, march, ...., Dec)) AS pvt)t
Or you can simply add a temp table which stores numbers from 1 to 12
inner join #temp on n>=datepart(mm,DateofTransaction) group by year(transaction), n

SQL - How to count records for each status in one line per day?

I have a table Sales
Sales
--------
id
FormUpdated
TrackingStatus
There are several status e.g. Complete, Incomplete, SaveforLater, ViewRates etc.
I want to have my results in this form for the last 8 days(including today).
Expected Result:
Date Part of FormUpdated, Day of Week, Counts of ViewRates, Counts of Sales(complete), Counts of SaveForLater
--------------------------------------
2015-05-19 Tuesday 3 1 21
2015-05-18 Monday 12 5 10
2015-05-17 Sunday 6 1 8
2015-05-16 Saturday 5 3 7
2015-05-15 Friday 67 5 32
2015-05-14 Thursday 17 0 5
2015-05-13 Wednesday 22 0 9
2015-05-12 Tuesday 19 2 6
Here is my sql query:
select datename(dw, FormUpdated), count(ID), TrackingStatus
from Sales
where FormUpdated <= GETDATE()
AND FormUpdated >= GetDate() - 8
group by datename(dw, FormUpdated), TrackingStatus
order by datename(dw, FormUpdated) desc
I do not know how to make the next step.
Update
I forgot to mention, I only need the Date part of the FormUpdated, not all parts.
You can use SUM(CASE WHEN TrackingStatus = 'SomeTrackingStatus' THEN 1 ELSE 0 END)) to get the status count for each tracking status in individual column. Something like this. SQL Fiddle
select
CONVERT(DATE,FormUpdated) FormUpdated,
DATENAME(dw, CONVERT(DATE,FormUpdated)),
SUM(CASE WHEN TrackingStatus = 'ViewRates' THEN 1 ELSE 0 END) c_ViewRates,
SUM(CASE WHEN TrackingStatus = 'Complete' THEN 1 ELSE 0 END) c_Complete,
SUM(CASE WHEN TrackingStatus = 'SaveforLater' THEN 1 ELSE 0 END) c_SaveforLater
from Sales
where FormUpdated <= GETDATE()
AND FormUpdated >= DATEADD(D,-8,GetDate())
group by CONVERT(DATE,FormUpdated)
order by CONVERT(DATE,FormUpdated) desc
You can also use a PIVOT to achieve this result - you'll just need to complete the list of TrackingStatus names in both the SELECT and the FOR, and no GROUP BY required:
WITH DatesOnly AS
(
SELECT Id, CAST(FormUpdated AS DATE) AS DateOnly, DATENAME(dw, FormUpdated) AS DayOfWeek, TrackingStatus
FROM Sales
)
SELECT DateOnly, DayOfWeek,
-- List of Pivoted Columns
[Complete],[Incomplete], [ViewRates], [SaveforLater]
FROM DatesOnly
PIVOT
(
COUNT(Id)
-- List of Pivoted columns
FOR TrackingStatus IN([Complete],[Incomplete], [ViewRates], [SaveforLater])
) pvt
WHERE DateOnly <= GETDATE() AND DateOnly >= GetDate() - 8
ORDER BY DateOnly DESC
SqlFiddle
Also, I think your ORDER BY is wrong - it should just be the Date, not day of week.

Show column name as months from past year starting from current_date

I am writing a report that shows the total amount of codes for each month since the past year.
Currently if I just do a count for all of the codes in the past year then my result set will look like this
name | code | total | date
build1 x1 10 04-2013
build1 x50 60 05-2013
build1 x1 80 06-2013
build1 x90 450 07-2013
I was able to transpose all of rows so all of the columns would be the month, with the total below it. My updated results look like this now
name | code | apl | may | jun | jul
build1 x1 10 0 80 0
build1 x50 0 60 0 0
build1 x90 0 0 0 450
The code above are the results i am looking for but what I am wanting to do now is to order everything by the current month and then back one year from that current month.
So if the current month is july then my result set would be ordered like this
name | code | jul | jun | may | apl
build1 x1 0 80 0 10
build1 x50 0 0 60 0
build1 x90 450 0 0 0
The problem I am running in to that that I am using alias's as the month names. And you cannot grab the month from an alias. Also, alias's as far as I know are static so they can't change once you have them set. The only way to get the month as a column name is to extract it from your data set. But when I transpose the rows into column I have to use alias's since I am using case statements to get all of the totals for each month.
EDIT: Sorry, postgresql version is 8.4, here is my query that i have so far
SELECT
pname,
code,
SUM(totaljanurary) AS "Janurary",
SUM(totalfebruary) AS "February",
SUM(totalmarch) AS "March",
SUM(totalapril) AS "April",
SUM(totalmay) AS "May",
SUM(totaljune) AS "June",
SUM(totaljuly) AS "July",
SUM(totalaugust) AS "August",
SUM(totalseptember) AS "September",
SUM(totaloctober) AS "October",
SUM(totalnovember) AS "November",
SUM(totaldecember) AS "December"
FROM(
SELECT
pname,
code,
SUM(case when extract (month FROM checked_date)=01 then total else 0 end) AS totaljanurary,
SUM(case when extract (month FROM checked_date)=02 then total else 0 end) AS totalfebruary,
SUM(case when extract (month FROM checked_date)=03 then total else 0 end) AS totalmarch,
SUM(case when extract (month FROM checked_date)=04 then total else 0 end) AS totalapril,
SUM(case when extract (month FROM checked_date)=05 then total else 0 end) AS totalmay,
SUM(case when extract (month FROM checked_date)=06 then total else 0 end) AS totaljune,
SUM(case when extract (month FROM checked_date)=07 then total else 0 end) AS totaljuly,
SUM(case when extract (month FROM checked_date)=08 then total else 0 end) AS totalaugust,
SUM(case when extract (month FROM checked_date)=09 then total else 0 end) AS totalseptember,
SUM(case when extract (month FROM checked_date)=10 then total else 0 end) AS totaloctober,
SUM(case when extract (month FROM checked_date)=11 then total else 0 end) AS totalnovember,
SUM(case when extract (month FROM checked_date)=12 then total else 0 end) AS totaldecember
FROM (
--START HERE
SELECT
pname,
code,
COUNT(code)AS total,
date_trunc('month',checked_date)::date AS checked_date
FROM table1
AND checked_date >= current_date-365
AND checked_date <= current_date
GROUP BY pname, code, date_trunc('month',checked_date)
)T1
GROUP BY pname, code, date_trunc('month',checked_date)
)T2
GROUP BY pname, code
ORDER BY pname, code
You want crosstab(), provided by the additional module tablefunc.
Assuming "date" is of type date (like it should be).
Other details depend on details you forgot to provide.
SELECT * FROM crosstab(
$$SELECT name, code, to_char("date", 'mon'), total
FROM tbl
WHERE "date" < now()
AND "date" >= now() - interval '1 year'
ORDER BY name, extract(month from now()) DESC$$
,$$VALUES
('dec'::text), ('nov'), ('oct'), ('sep'), ('aug'), ('jul')
, ('jun'), ('may'), ('apr'), ('mar'), ('feb'), ('jan')$$
)
AS ct (name text, code text
, dec int, nov int, oct int, sep int, aug int, jul int
, jun int, may int, apr int, mar int, feb int, jan int);
Refer to this closely related answer for additional instructions:
Sum by month and put months as columns
You shouldn't be using date as identifier, it's a reserved word. I double-quoted it.
You shouldn't be using the non-descriptive name name either.