I am having an issue getting a record produced if my count = 0.
Basically my query is counting logons based on some criteria, but if there has never been a logon for a specific customerID I still want it to show as 0.
I have tried IFNULL on the count but with no joy.
SELECT
CUSTOMERID,
CASE
WHEN STATUSCODE = 600 THEN 'Successful Logon'
ELSE 'Unsuccessful Logon'
END as LogonStatus,
COUNT( * ) COUNTOFACCOUNTS
FROM
SCEMEA.TABLENAME
WHERE
CUSTOMERID in ('"+join(Parameters!CustomerID.Value, "','")+"')
AND (Cast(DATETIME as Date) >= '"& Format(Parameters!FromDate.Value, "yyyy-MM-dd") & "'
AND Cast(DATETIME as Date) <= '" & Format(Parameters!ToDate.Value, "yyyy-MM-dd") & "')
AND COMPONENTDESCRIPTION = 'RandomText'
AND METHOD = 'RandomText'
GROUP BY
CUSTOMERID,
CASE
WHEN STATUSCODE = 600 THEN 'Successful Logon'
ELSE 'Unsuccessful Logon'
END
ORDER BY
CUSTOMERID ASC
Please let me know if you need anymore information, any help would be appreciated.
Related
I am having trouble writing this sql query. Basically I need to find the top 100 sCompanys who had the most nSales within the last 365 days, but had zero sales before 365 days. This is being done in node so its a string, I am also passing in parameters. Start date is the date for 365 days ago.
This is not throwing any errors when I run it, however it also is not returning any data.
getMostSales365NoneBefore(startDate) {
let sqlQuery = '';
sqlQuery =
"SELECT TOP 100 SUM(nQuoteTotal) AS nSales, sCompany FROM Customer_Quotes WHERE (bDeleted=0 AND sStatus='Closed' AND dtFirstClosed > " +
"'" +
startDate +
"')" +
' AND (nSales < ' +
"'" +
startDate +
"') IS NOT NULL" +
' GROUP BY sCompany ORDER BY nSales DESC';
console.log(sqlQuery);
return sqlQuery;
}, ```
You should parameterize your query properly, and pass through #startDate as a parameter.
Note that you cannot refer to aggregates in the WHERE part, only in the HAVING, ORDER BY or SELECT
The query you want would look like this
SELECT TOP (100)
SUM(CASE WHEN dtFirstClosed >= #startDate THEN nQuoteTotal END) AS nSales,
sCompany
FROM Customer_Quotes
WHERE bDeleted = 0
AND sStatus = 'Closed'
GROUP BY sCompany
HAVING COUNT(CASE WHEN dtFirstClosed < #startDate THEN 1 END) = 0
ORDER BY nSales DESC
I track the aging of customer invoices.
The below code example returns the balance of customer invoices by customer that are between 0 and 30 days old.
However, I want to run one query that pulls separate columns into Excel for each customer's balance aged between 0 and 30 days, 31 and 60, 61 and 90, and finally over 90 days.
I am hoping to pull this into Excel so the columns are as follows-
Customer Number, Customer Name, Balance(That is under 30 days old), Balance(30-59 days), Balance(60-90), Balance(Over 90)
vtSql = ""
vtSql = vtSql & " SELECT CUSTNUM, CUSTNAME, SUM(BALANCE) "
vtSql = vtSql & " FROM VIEWALLINVOICES "
vtSql = vtSql & " WHERE BALANCE <> '0' AND INVDATE BETWEEN #" & Application.Text(Range("TODAY") - 30, "mm/dd/yyyy") & "# AND #" & Application.Text(Range("TODAY"), "mm/dd/yyyy") & "#"
vtSql = vtSql & " GROUP BY CUSTNUM, CUSTNAME "
vtSql = vtSql & " ORDER BY SUM(BALANCE) DESC;"
I am using a MS Access database and I am pulling this directly into Excel using an ADODB Connection and "Microsoft.Jet.OLEDB.4.0".
You seem to want conditional aggregation. In MS-Access, you should be able to phrase this as:
SELECT CUSTNUM, CUSTNAME,
SUM(IIF(INVDATE BETWEEN DateAdd('d', -30, date()) AND date() , BALANCE, 0)) AS BALANCE_0_30,
SUM(IIF(INVDATE BETWEEN DateAdd('d', -60, date()) AND DateAdd('d', -31, date()), BALANCE, 0)) AS BALANCE_31_60,
SUM(IIF(INVDATE BETWEEN DateAdd('d', -90, date()) AND DateAdd('d', -61, date()), BALANCE, 0)) AS BALANCE_61_90,
SUM(IIF(INVDATE <= DateAdd('d', -91, date()) , BALANCE, 0)) AS BALANCE_OVER_91
FROM VIEWALLINVOICES
GROUP BY CUSTNUM, CUSTNAME
This computes the dates ranges dynamically by offseting the current date - which is how I understood your question.
I have created a CommandButton within Excel and started coding VBA.
The idea is to pass parameters to my CommandString so that the user can filter.
The 2 parameter fields are of datatype smalldatetime within SQL
Here is my VBA code which executes after I Click the CommandButton :
Private Sub CommandButton1_Click()
Dim FromDate As Date
Dim ToDate As Date
FromDate = Sheets("Bips Travel Summary").Range("J3").Value
ToDate = Sheets("Bips Travel Summary").Range("J4").Value
'Pass the Parameters values to the Stored Procedure used in the Data Connection
With ActiveWorkbook.Connections("192.168.0.3 Timesheets1").OLEDBConnection
.CommandText = "SELECT ID, Employee, WT, [Amount Per Kilometer], Currency, SUM([Number (Amount of km)]) AS [Number (Amount of km)], SUM([Total (per record)]) AS [Total (per record)] FROM ( SELECT S.ID ,S.FirstName + ' ' + S.LastName AS [Employee],TS.DateWorked AS [DateTraveled],C.Customer_Name,NULL AS [WT],EC.AA_Rate AS [Amount Per Kilometer],NULL AS [Currency],TS.Travel AS [Number (Amount of km)],TT.TravelDescription,TS.Travel * CONVERT(float, EC.AA_Rate) AS [Total (per record)] FROM [Timesheets].[dbo].[timesheets] TS INNER JOIN [Timesheets].[dbo].[traveltype] TT ON TS.TravelTypeCode = TT.TravelTypeCode INNER JOIN [Timesheets].[dbo].[staff] S ON TS.Staff_Code = S.Staff_Code INNER JOIN [Timesheets].[dbo].[enginecapacity] EC ON TS.EngineCapacityCode = EC.EngineCapacityCode INNER JOIN [Timesheets].[dbo].[customers] C ON TS.Cust_Code = C.Cust_Code WHERE TS.DateWorked BETWEEN '" & FromDate & "' AND '" & ToDate & "') as A GROUP BY ID, Employee, WT, [Amount Per Kilometer], Currency"
ActiveWorkbook.Connections("192.168.0.3 Timesheets1").Refresh
End With
End Sub
After entering the value for FromDate as 20100101
and ToDate as 20150813 I get an error message which falls over on this script:
FromDate = Sheets("Bips Travel Summary").Range("J3").Value
Error message reads :
Runtime error '13':
Type mismatch
Not sure where to go from here as I am very new to VBA.
Could anyone please point me in the right direction to solve this issue?
The error says that you are trying to assign the wrong data type.
Variables FromDate and ToDate are declared as Date type, but you are trying to assign texts to them.
If you have dates in this format in your cells: '20100101' and '20150813', you need to convert them to dates before assigning to those variables like below:
Private Sub CommandButton1_Click()
Dim txtFromDate As String
Dim txtToDate As String
Dim FromDate As Date
Dim ToDate As Date
txtFromDate = Sheets("Bips Travel Summary").Range("J3").Value
FromDate = DateSerial(Left(txtFromDate, 4), Mid(txtFromDate, 5, 2), Right(txtFromDate, 2))
txtToDate = Sheets("Bips Travel Summary").Range("J4").Value
ToDate = DateSerial(Left(txtToDate, 4), Mid(txtToDate, 5, 2), Right(txtToDate, 2))
'Pass the Parameters values to the Stored Procedure used in the Data Connection
With ActiveWorkbook.Connections("192.168.0.3 Timesheets1").OLEDBConnection
.CommandText = "SELECT ID, Employee, WT, [Amount Per Kilometer], Currency, SUM([Number (Amount of km)]) AS [Number (Amount of km)], SUM([Total (per record)]) AS [Total (per record)] FROM ( SELECT S.ID ,S.FirstName + ' ' + S.LastName AS [Employee],TS.DateWorked AS [DateTraveled],C.Customer_Name,NULL AS [WT],EC.AA_Rate AS [Amount Per Kilometer],NULL AS [Currency],TS.Travel AS [Number (Amount of km)],TT.TravelDescription,TS.Travel * CONVERT(float, EC.AA_Rate) AS [Total (per record)] FROM [Timesheets].[dbo].[timesheets] TS INNER JOIN [Timesheets].[dbo].[traveltype] TT ON TS.TravelTypeCode = TT.TravelTypeCode INNER JOIN [Timesheets].[dbo].[staff] S ON TS.Staff_Code = S.Staff_Code INNER JOIN [Timesheets].[dbo].[enginecapacity] EC ON TS.EngineCapacityCode = EC.EngineCapacityCode INNER JOIN [Timesheets].[dbo].[customers] C ON TS.Cust_Code = C.Cust_Code WHERE TS.DateWorked BETWEEN '" & FromDate & "' AND '" & ToDate & "') as A GROUP BY ID, Employee, WT, [Amount Per Kilometer], Currency"
ActiveWorkbook.Connections("192.168.0.3 Timesheets1").Refresh
End With
End Sub
I have this SQL:
SELECT (Min(Time_In) & " to " & Max(Time_Out)) AS [Week Of],
Round((Sum(DATEDIFF("n", Time_In, Time_Out))/Count(DATEDIFF("n", Time_In, Time_Out))),2) AS [Avg Min of Jog]
FROM SomeTable
WHERE len(Time_In) > 0 AND len(Time_Out) > 0
AND #01/01/2012# <= Time_In AND #12/31/2012# >= Time_In
GROUP BY DatePart('ww',Time_In);
Which picks out average times of a jog per week. I would also like to include a count how many times jogged per week, which I'm trying to do by counting the jog_id where SomeTable could have 5 entries for one jog_id.
I have tried:
SELECT (Min(Time_In) & " to " & Max(Time_Out)) AS [Week Of],
Round((Sum(DATEDIFF("n", Time_In, Time_Out))/Count(DATEDIFF("n", Time_In, Time_Out))),2) AS [Avg Min of Jog],
Count(distinct jog_id) AS [Num Jogs]
FROM SomeTable
WHERE len(Time_In) > 0 AND len(Time_Out) > 0
AND #01/01/2012# <= Time_In AND #12/31/2012# >= Time_In
GROUP BY DatePart('ww',Time_In);
But this is giving me Syntax error (missing operator) in query expression 'Count(distinct jog_id)'.
What am I missing?
You can't do this in Access without using a sub-query.
EX:
SELECT Count(*)
FROM
(SELECT DISTINCT Name FROM table1);
Here is a detailed article on the topic:
Access refuses to do good in nearly all circumstances, one of which is the support of the Count(distinct x).
CurrentMonth = Month(CurrentDate)
CurrentYear = Year(CurrentDate)
SQL = "SELECT Spent, MONTH(Date) AS InvMonth, YEAR(Date) As InvYear FROM Invoices WHERE YEAR(Date) = '" & CurrentYear & "' AND MONTH(Date) = '" & CurrentMonth & "'"
RecordSet.Open SQL, Connection, adOpenStatic, adLockOptimistic, adCmdText
Do Until RecordSet.EOF
MTotal(i) = MTotal(i) + RecordSet.Fields("Spent")
RecordSet.MoveNext
Loop
RecordSet.Close
This is the code I currently have to build up a total spent for a given month.
I wish to expand this to retrieve the totals per month, for the past 12 months.
The way I see to do this would be to loop backwards through the CurrentMonth value, and if CurrentMonth value reaches 0 roll the value of CurrentYear back 1. Using the loop variable (i) to build up an array of 12 values: MTotal()
What do you guys think?
A group by should get you on the way.
SELECT TOP 12
SUM(Spent) AS Spent
, MONTH(Date) AS InvMonth
, YEAR(Date) AS InvYear
FROM
Invoices
GROUP BY
YEAR(Date), MONTH(Date)
WHERE DATEDIFF(mm, Date, GETDATE(()) < 12
Josh's DATEDIFF is a better solution than my original TOP and ORDER BY
I would tackle this by "rounding" the date to the Month, and then Grouping by that month-date, and totalling the Spent amount:
SELECT SUM(Spent) AS [TotalSpent],
DATEADD(Month, DATEDIFF(Month, 0, [Date]), 0) AS [MonthDate]
FROM Invoices
WHERE [Date] >= '20080301'
AND [Date] < '20090301'
GROUP BY DATEADD(Month, DATEDIFF(Month, 0, [Date]), 0)
ORDER BY [MonthDate]
The [MonthDate] can be formatted to show Month / Date appropraitely, or in separate columns.
The WHERE clause can be parameterised to provide a suitable range of records to be included
The only problem with this is that I require a monthly total, for each of the past 12 months rather then the total for the past 12 months. Otherwise I see how improving the SQL rather then using vb6 code oculd be a better option.
The solution I came up with would be :
For i = 0 To 11
If CurrentMonth = 0 Then
CurrentMonth = 12
CurrentYear = CurrentYear - 1
End If
SQL = "SELECT Spent, MONTH(Date) AS InvMonth, YEAR(Date) As InvYear FROM Invoices WHERE YEAR(Date) = '" & CurrentYear & "' AND MONTH(Date) = '" & CurrentMonth & "'"
RecordSet.Open SQL, Connection, adOpenStatic, adLockOptimistic, adCmdText
Do Until RecordSet.EOF
MTotal(i) = MTotal(i) + RecordSet.Fields("Spent").Value
RecordSet.MoveNext
Loop
RecordSet.Close
CurrentMonth = CurrentMonth - 1
Next
I believe this should work as expected. However I still look forward to seeing what solutions you guys can come up, or if anyone spots an issue with ym fix.