I need to add additional columns to my application that are not part of GROUPBY statement - sql

I need some help with my SQL command. I have a VB.net application that uses few sql tables to get the final result. I need to add few additional columns from TableC into my application, but these columns are not part of GROUPBY function.
I tried to add simple select function to the code, but I always get the same error:
$"
SET NOCOUNT ON;
SELECT CONVERT(VARCHAR(10), r.PossibleDate, 120) as [Date],
**SELECT r.GStart as GStart,**
SUM(ISNULL(r.ElecCheckIn, 0)) as CheckIn,
SUM(ISNULL(r.ElecCheckOut, 0)) as CheckOut,
SUM(ISNULL(r.JPAmount, 0)) as AttAmountJP,
SUM(ISNULL(r.MeteredAttAmountCC, 0)) as AttAmountCC,
SUM(ISNULL(r.MeteredMachAmount, 0)) as MachAmount,
SUM(ISNULL(r.MeteredAttAmount, 0)) as AttAmount,
SUM(ISNULL(r.ElecCheckIn, 0) - ISNULL(r.ElecCheckOut, 0) - ISNULL(r.JPAmount, 0) - ISNULL(r.MeteredAttAmountCC, 0) - ISNULL(r.MeteredMachAmount, 0) - ISNULL(r.MeteredAttAmount, 0)) as NetWin
FROM dbo.CDS_TableA sm (NOLOCK)
INNER JOIN dbo.bb_tableB st (NOLOCK)
ON sm.TableB_Id=st.SlotB_Id
AND sm.TableBRevision=st.TabelBRevision
INNER JOIN dbo.TableC r (NOLOCK)
ON sm.TableA_ID=r.TableA_ID
AND r.PossibleDate BETWEEN '{dtStart.Value.ToString("yyyy-MM-dd")} 00:00:00' AND '{dtEnd.Value.ToString("yyyy-MM-dd")} 23:59:59'
AND r.Period_ID=4
INNER JOIN dbo.BB_TableD rh (NOLOCK)
ON sm.TableA_ID=rh.TableA_ID
AND r.PossibleDate=rh.PossibleDate
AND sm.Revision=rh.Revision
WHERE sm.OnFloorFlag = 1
AND sm.Calc_ID NOT IN (2,5)
GROUP BY r.PossibleDate
ORDER BY r.PossibleDate;
I always get an error that GStart is not contained in either an aggregate function or the GROUP BY clause.

Simply JOIN the aggregate level to unit level which can be facilitated with a CTE. Run this entire statement below including WITH clause.
WITH agg AS (
SELECT CONVERT(VARCHAR(10), r.PossibleDate, 120) as [Date],
SUM(ISNULL(r.ElecCheckIn, 0)) as CheckIn,
SUM(ISNULL(r.ElecCheckOut, 0)) as CheckOut,
SUM(ISNULL(r.JPAmount, 0)) as AttAmountJP,
SUM(ISNULL(r.MeteredAttAmountCC, 0)) as AttAmountCC,
SUM(ISNULL(r.MeteredMachAmount, 0)) as MachAmount,
SUM(ISNULL(r.MeteredAttAmount, 0)) as AttAmount,
SUM(ISNULL(r.ElecCheckIn, 0) -
ISNULL(r.ElecCheckOut, 0) -
ISNULL(r.JPAmount, 0) -
ISNULL(r.MeteredAttAmountCC, 0) -
ISNULL(r.MeteredMachAmount, 0) -
ISNULL(r.MeteredAttAmount, 0)) as NetWin
FROM dbo.CDS_TableA sm (NOLOCK)
INNER JOIN dbo.bb_tableB st (NOLOCK)
ON sm.TableB_Id =s t.SlotB_Id
AND sm.TableBRevision=st.TabelBRevision
INNER JOIN dbo.TableC r (NOLOCK)
ON sm.TableA_ID= r.TableA_ID
AND r.PossibleDate BETWEEN '{dtStart.Value.ToString("yyyy-MM-dd")} 00:00:00'
AND '{dtEnd.Value.ToString("yyyy-MM-dd")} 23:59:59'
AND r.Period_ID=4
INNER JOIN dbo.BB_TableD rh (NOLOCK)
ON sm.TableA_ID=rh.TableA_ID
AND r.PossibleDate=rh.PossibleDate
AND sm.Revision=rh.Revision
WHERE sm.OnFloorFlag = 1
AND sm.Calc_ID NOT IN (2,5)
GROUP BY r.PossibleDate
)
SELECT r.GStart as GStart, agg.* --- ADD OTHER r FIELDS
FROM dbo.TableC r
INNER JOIN agg ON CONVERT(VARCHAR(10), r.PossibleDate, 120) = agg.[Date]
ORDER BY r.PossibleDate
Aside: While I know nothing of vb.net, I do know running SQL at application layer and your concatenation of dates above should be parameterized values which is a programming industry best practice. See How do I create a parameterized SQL query? Why Should I? Also, use NOLOCK with caution.

Related

Not include this specific date in the query when using BETWEEN operator in SQL Server 2008

There is one specific date that I do not want to include in this which is "04/08/2020". I want to filter all the records from the beginning of the year till now but not 04/08/2020. How can I do that?
SELECT
dbo.PID_RespiratorFit.PTIDNum,
rtrim(acp.LastName) + ', ' + rtrim(acp.FirstName) AS Name,
acp.BadgeID AS ID,
dbo.Patient.PcFLD01 as Organization,
dbo.PID_RespiratorFit.Risk AS Exposure,
UPPER(dbo.PID_RespiratorFit.Type) AS Mask_Type,
dbo.PID_RespiratorFit.OHSNotes AS Comments,
dbo.PID_RespiratorFit.MedicallyClearedDate AS Medically_Cleared,
dbo.PID_RespiratorFit.TrainingCompletedDate,
dbo.PID_RespiratorFit.DateIssued AS N95_Fittest_Completed,
dbo.PID_RespiratorFit.Mask AS N95_respirator,
dbo.PID_RespiratorFit.PAPR,
dbo.PID_RespiratorFit.PaprFitTestDate AS PAPR_Fittest_Completed,
dbo.PID_RespiratorFit.Active,
DATEADD(year, 1, dbo.PID_RespiratorFit.MedicallyClearedDate) AS Compliant_Through
FROM dbo.PID_RespiratorFit LEFT JOIN
dbo.Patient ON dbo.PID_RespiratorFit.PTIDNum = dbo.Patient.PTIDNUM LEFT JOIN
dbo.aspnet_CustomProfile acp ON dbo.Patient.PGuid = acp.UserId
WHERE (dbo.PID_RespiratorFit.DateIssued BETWEEN '1-1-2020' AND Getdate())
Use standard date formats! Then:
WHERE dbo.PID_RespiratorFit.DateIssued BETWEEN '2020-01-01' AND Getdate() and
dbo.PID_RespiratorFit.DateIssued <> '2020-04-08' -- or is that 2020-08-04???
If the date is really a date/time, then use:
WHERE dbo.PID_RespiratorFit.DateIssued BETWEEN '2020-01-01' AND Getdate() and
CONVERT(DATE, dbo.PID_RespiratorFit.DateIssued) <> '2020-04-08' -- or is that 2020-08-04???
I also strongly recommend table aliases so the query is much easier to write and read. For example:
SELECT . . .
FROM dbo.PID_RespiratorFit rf LEFT JOIN
dbo.Patient p
ON rf.PTIDNum = p.PTIDNUM LEFT JOIN
dbo.aspnet_CustomProfile acp
ON p.PGuid = acp.UserId
WHERE rf.DateIssued BETWEEN '2020-01-01' AND Getdate() AND
CONVERT(DATE, rf.DateIssued) <> '2020-04-08' -- or is that 2020-08-04???
You can try the below - adding an extra condition
SELECT
dbo.PID_RespiratorFit.PTIDNum,
rtrim(acp.LastName) + ', ' + rtrim(acp.FirstName) AS Name,
acp.BadgeID AS ID,
dbo.Patient.PcFLD01 as Organization,
dbo.PID_RespiratorFit.Risk AS Exposure,
UPPER(dbo.PID_RespiratorFit.Type) AS Mask_Type,
dbo.PID_RespiratorFit.OHSNotes AS Comments,
dbo.PID_RespiratorFit.MedicallyClearedDate AS Medically_Cleared,
dbo.PID_RespiratorFit.TrainingCompletedDate,
dbo.PID_RespiratorFit.DateIssued AS N95_Fittest_Completed,
dbo.PID_RespiratorFit.Mask AS N95_respirator,
dbo.PID_RespiratorFit.PAPR,
dbo.PID_RespiratorFit.PaprFitTestDate AS PAPR_Fittest_Completed,
dbo.PID_RespiratorFit.Active,
DATEADD(year, 1, dbo.PID_RespiratorFit.MedicallyClearedDate) AS Compliant_Through
FROM dbo.PID_RespiratorFit LEFT JOIN
dbo.Patient ON dbo.PID_RespiratorFit.PTIDNum = dbo.Patient.PTIDNUM LEFT JOIN
dbo.aspnet_CustomProfile acp ON dbo.Patient.PGuid = acp.UserId
WHERE (dbo.PID_RespiratorFit.DateIssued BETWEEN '1-1-2020' AND Getdate())
AND cast(dbo.PID_RespiratorFit.DateIssued as date)<>'2020-04-08'

How could I join these queries together?

I have 2 queries. One includes a subquery and the other is a pretty basic query. I can't figure out how to combine them to return a table with name, workdate, minutes_inactive, and hoursworked.
I have the code below for what I have tried. The simple query is lines 1,2, and the last 5 lines. I also added a join clause (join punchclock p on p.servrepID = l.repid) to it.
Both these queries ran on their own so this is solely just the problem of combining them.
select
sr.sr_name as liaison, cast(date_created as date) workdate,
(count(date_created) * 4) as minutes_inactive,
(select
sr_name, cast(punchintime as date) as workdate,
round(sum(cast(datediff(minute,punchintime, punchouttime) as real) / 60), 2) as hoursworked,
count(*) as punches
from
(select
sr_name, punchintime = punchdatetime,
punchouttime = isnull((select top 1 pc2.punchdatetime
from punchclock pc2
where pc2.punchdatetime > pc.punchdatetime
and pc.servrepid = pc2.servrepid
and pc2.inout = 0
order by pc2.punchdatetime), getdate())
from
punchclock pc
join
servicereps sr on pc.servrepid = sr.servrepid
where
punchyear >= 2017 and pc.inout = 1
group by
sr_name, cast(punchintime as date)))
from
tbl_liga_popup_log l
join
servicereps sr on sr.servrepID = l.repid
join
punchclock p on p.servrepID = l.repid collate latin1_general_bin
group by
cast(l.date_created as date), sr.sr_name
I get this error:
Msg 102, Level 15, State 1, Line 19
Incorrect syntax near ')'
I keep getting this error but there are more errors if I adjust that part.
I don't know that we'll fix everything here, but there are a few issues with your query.
You have to alias your sub-query (technically a derived table, but whatever)
You have two froms in your outer query.
You have to join to the derived table.
Here's an crude example:
select
<some stuff>
from
(select col1 from table1) t1
inner join t2
on t1.col1 = t2.col2
The large error here is that you are placing queries in the select section (before the from). You can only do this if the query returns a single value. Else, you have to put your query in a parenthesis (you have done this) in the from section, give it an alias, and join it accordingly.
You also seem to be using group bys that are not needed anywhere. I can't see aggregation functions like sum().
My best bet is that you are looking for the following query:
select
sr_name as liaison
,cast(date_created as date) workdate
,count(distinct date_created) * 4 as minutes_inactive
,cast(punchintime as date) as workdate
,round(sum(cast(datediff(minute,punchintime,isnull(pc2_query.punchouttime,getdate())) as real) / 60), 2) as hoursworked
,count(*) as punches
from
punchclock pc
inner join servicereps sr on pc.servrepid = sr.servrepid
cross apply
(
select top 1 pc2.punchdatetime as punchouttime
from punchclock pc2
where pc2.punchdatetime > pc.punchdatetime
and pc.servrepid = pc2.servrepid
and pc2.inout = 0
order by pc2.punchdatetime
)q1
inner join tbl_liga_popup_log l on sr.servrepID = l.repid
where punchyear >= 2017 and pc.inout = 1

SQL - SELECT subquery AS BIT value for EXIST check

I have a problem.
I'm trying to get a BIT value to check whether a person has entered the building last night between 10pm to midnight. When I run the subquery code by itself, it gives me the results I need. As I'm working with SSRS2008 I need for all the results to be in the same stored procedure.
So the problem is, it gives me the bit values somewhat right, for the ones that are obviously false, it gives false, for the ones that are obviously true, it gives true. But for the ones in the middle (the day shift, who leave at 23) it gives the results somewhat random..
Does anyone have a clue?
SELECT DISTINCT TOP 200
Events.LoggedTime,
PTUsers.Name,
PTDoors.PTDoorsID,
PTUsers.AccessLevel,
CAST(CASE
WHEN EXISTS (SELECT Events.LoggedTime
FROM Events
INNER JOIN PTUsers AS PTUsers_1 ON Events.GlobalIndex1 = PTUsers.GlobalRecord
INNER JOIN PTDoors AS PTDoors_1 ON Events.RecordIndex2 + 1 = PTDoors.Address
WHERE (DATEPART(day, Events.LoggedTime) = DATEPART(day, GETDATE() - 1))
AND (DATEPART(hour, Events.LoggedTime) IN (22, 23))
AND (PTDoors_1.PTDoorsID = 14)) THEN 1 ELSE 0 END AS BIT) AS Night
FROM
Events
INNER JOIN
PTUsers ON Events.GlobalIndex1 = PTUsers.GlobalRecord
INNER JOIN
PTDoors ON Events.RecordIndex2 + 1 = PTDoors.Address
WHERE
(PTUsers.Panel = 0)
AND (PTDoors.Panel = 0)
AND (PTDoors.PTDoorsID = 14)
AND (DATEPART(day, Events.LoggedTime) = DATEPART(day, GETDATE()) - 1)
AND (PTUsers.AccessLevel IN (3))
ORDER BY
Events.LoggedTime DESC
#lrd i did the corrections you suggested,
thanks for pointing out the table aliases :)
i removed the cast, so now i get the BIT column. but now the problem is that i get all "1"'s as results.
What baffles me is the that subquery works as it should as a query on it's own. it goes back a day, and displays the entries on that door in the given timeframe.
now i'm trying to compare that information for the same person, meaning - i see a person in the list, arriving yesterday at 6am, check if that person also arrived the day before that between 22 & midnight and return a bit value to display that.
SELECT DISTINCT TOP 200 Events.LoggedTime, PTUsers.Name, PTDoors.PTDoorsID, PTUsers.AccessLevel, CASE WHEN EXISTS
(SELECT Events.LoggedTime
FROM Events INNER JOIN
PTUsers AS PTUsers_1 ON Events.GlobalIndex1 = PTUsers_1.GlobalRecord INNER JOIN
PTDoors AS PTDoors_1 ON Events.RecordIndex2 + 1 = PTDoors_1.Address
WHERE (DATEPART(day, Events.LoggedTime) = DATEPART(day, GETDATE() - 1)) AND (DATEPART(hour, Events.LoggedTime) IN (22, 23)) AND
(PTDoors_1.PTDoorsID = 14)) THEN 1 ELSE 0 END AS BIT
FROM Events INNER JOIN
PTUsers ON Events.GlobalIndex1 = PTUsers.GlobalRecord INNER JOIN
PTDoors ON Events.RecordIndex2 + 1 = PTDoors.Address
WHERE (PTUsers.Panel = 0) AND (PTDoors.Panel = 0) AND (PTDoors.PTDoorsID = 14) AND (DATEPART(day, Events.LoggedTime) = DATEPART(day, GETDATE())
- 1) AND (PTUsers.AccessLevel IN (3))
ORDER BY Events.LoggedTime DESC
I don't think you need a CAST because you are explicitly defining Night as a BIT By setting the result to EXISTS(), which is a bit. I removed the query that was incorrect.
I see your problem. You are not using the correct table alias for your join constraint in your subquery.
It should be:
INNER JOIN PTUsers AS PTUsers_1 ON Events.GlobalIndex1 = PTUsers_1.GlobalRecord
INNER JOIN PTDoors AS PTDoors_1 ON Events.RecordIndex2 + 1 = PTDoors_1.Address
Also,check and make sure you are using the correct values in your join. I would change the following for a test.
FROM Events Events_2
INNER JOIN PTUsers AS PTUsers_1 ON Events_2.GlobalIndex1 = PTUsers_1.GlobalRecord
INNER JOIN PTDoors AS PTDoors_1 ON Events_2.RecordIndex2 + 1 = PTDoors_1.Address

Adding zero values to report

Ok This is a good question I think.
At the moment I have a report showing amount of tickets per machine and how much each machine made in ticket sales.
Some machines sell Zero tickets but they are not includded in my report.
Now i want to include them.
there is a full list of all machines in machconfig table which I could compare to the ticketssold table which also has a field corresponding to the machine that sold it.
So I guess I could find all of the machines that havent sold any tickets by looking for machine id's (MCHterminalid) that dont appear in the ticketssold table (TKtermid column)
here is the code I've got so far..
SELECT TKtermID,
MCHlocation,
Count (TKvouchernum) AS Totaltickets,
Cast(Sum(TKcomission) AS FLOAT) / 100 AS Total_Comission
FROM ticketssold(NOLOCK)
INNER JOIN machconfig (NOLOCK)
ON MCHterminalID = TKtermID
WHERE cfglocationcountry = 'UK'
AND dateadded BETWEEN Getdate() - 100 AND Getdate()
GROUP BY vstermID,
cfglocation
ORDER BY Total_comission DESC
Change the inner join between ticketssold and machconfig to a right outer join to get all machines, regardless of a match in the tickets sold table. The count of TKVouchernum will return the zeros for you:
SELECT TKtermID,
MCHlocation,
Count (TKvouchernum) AS Totaltickets,
Cast(Sum(TKcomission) AS FLOAT) / 100 AS Total_Comission
FROM ticketssold(NOLOCK)
RIGHT OUTER JOIN machconfig (NOLOCK)
ON MCHterminalID = TKtermID
WHERE cfglocationcountry = 'UK'
AND dateadded BETWEEN DateAdd(DAY, -100, GetDate()) AND Getdate()
GROUP BY vstermID,
cfglocation
ORDER BY Total_comission DESC
OCD Version not totally proofed (also killing me that table names are not included before the fields). Use the outer join in combination with COALESCE
SELECT
TKTermID TicketTerminalId,
MchLocation MachineLocation,
COALESCE(COUNT(TKVoucherNum),0) TotalTickets,
COALESCE(CAST(SUM(TKComission) AS float),0) / 100 TotalComission
FROM
MachConfig (NOLOCK)
LEFT JOIN
TicketsSold (NOLOCK)
ON
TKtermID = MCHterminalID
WHERE
CfgLocationCountry = 'UK'
AND
DateAdded BETWEEN DATEADD(DAY, -100, GETDATE()) AND GETDATE()
GROUP BY
VSTermID,
CfgLocation
ORDER BY
COALESCE(CAST(SUM(TKComission) AS float),0) / 100 DESC; --Do this in reporting!
Do not use inner joins because they will eliminate rows. I start my joins with the table that has all the data. In this case machconfig and then do a left outer join to the table with the problematic data ticketssold.
You may also want to think about doing your grouping on the report side for flexibility.
Finally got it working the way I want.. Here is the proper code:
SELECT MCHTerminalID, MCHLocation, ISNULL(CONVERT(varchar(16), batch.LastBatchIn, 103),
'Did not batch in') AS LastBatchIn,
ISNULL(COUNT(Ticket.VoucherNum), 0) AS TotalVouchers,
ISNULL(SUM(Ticket.Sale), 0) AS TotalGrossAmount, ISNULL(SUM(Ticket.Refund),0) AS TotalRefundAmount, ISNULL(SUM(Ticket.Comission),0) AS TotalComission
FROM termConfig AS config WITH (NOLOCK)
LEFT OUTER JOIN
(SELECT bsTerminalID, MAX(bsDateTime) AS LastBatchIn
FROM batchSummary WITH (NOLOCK)
WHERE bsDateTime BETWEEN getdate()-50 AND getdate()
GROUP BY bsTerminalID
)
AS batch
ON config.MCHTerminalID = batch.bsTerminalID
LEFT OUTER JOIN
(SELECT DISTINCT TKTermID,
TKVoucherNum AS VoucherNum,
CAST(TKGrossTotal AS float)/100 AS Sale,
CAST(TKRefundAmount AS float)/100 AS Refund,
CAST(TKComission AS float)/100 AS Comission
FROM TicketVouchers WITH (NOLOCK)
WHERE dateAdded BETWEEN getdate()-50 AND getdate()
)
AS Ticket
ON
config.MCHTerminalID = Ticket.TKTermID
WHERE
config.MCHLocationCountry = 'uk'
AND config.MCHProductionTerminal = 'Y'
GROUP BY config.MCHTerminalID, config.MCHLocation, LastBatchIn
ORDER BY TotalComission desc
You could UNION the 'zero' rows to your original e.g.
<original query here>
...
UNION
SELECT MCHterminalID,
MCHlocation,
0 AS Totaltickets,
0 AS Total_Comission
FROM machconfig
WHERE NOT EXISTS (
SELECT *
FROM ticketssold
WHERE MCHterminalID = TKtermID
)
(Review for hints).

Changing a SUM returned NULL to zero

I have a stored procedure as follows:
CREATE PROC [dbo].[Incidents]
(#SiteName varchar(200))
AS
SELECT
(
SELECT SUM(i.Logged)
FROM tbl_Sites s
INNER JOIN tbl_Incidents i
ON s.Location = i.Location
WHERE s.Sites = #SiteName AND i.[month] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0)
GROUP BY s.Sites
) AS LoggedIncidents
'tbl_Sites contains a list of reported on sites.
'tbl_Incidents contains a generated list of total incidents by site/date (monthly)
'If a site doesn't have any incidents that month it wont be listed.
The problem I'm having is that a site doesn't have any Incidents this month and as such i got a NULL value returned for that site when i run this proc, but i need to have a zero/0 returned to be used within a chart in SSRS.
I've tried using coalesce and isnull to no avail.
SELECT COALESCE(SUM(c.Logged,0))
SELECT SUM(ISNULL(c.Logged,0))
Is there a way to get this formatted correctly?
Cheers,
Lee
Put it outside:
SELECT COALESCE(
(
SELECT SUM(i.Logged)
FROM tbl_Sites s
INNER JOIN tbl_Incidents i
ON s.Location = i.Location
WHERE s.Sites = #SiteName AND i.[month] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0)
GROUP BY s.Sites
), 0) AS LoggedIncidents
If you are returning multiple rows, change INNER JOIN to LEFT JOIN
SELECT COALESCE(SUM(i.Logged),0)
FROM tbl_Sites s
LEFT JOIN tbl_Incidents i
ON s.Location = i.Location
WHERE s.Sites = #SiteName AND i.[month] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0)
GROUP BY s.Sites
By the way, don't put any function or expression inside aggregate functions if it's not warranted, e.g. don't put ISNULL, COALESCE inside of SUM, using function/expression inside aggregation cripples performance, the query will be executed with table scan
You'll have to use ISNULL like this -
ISNULL(SUM(c.Logged), 0)
Or, as Michael said, you can use a Left Outer Join.
I encountered this problem in Oracle.
Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve the same result:
NVL(SUM(c.Logged), 0)
The easiest, and most readable, way I've found to accomplish this is through:
CREATE PROC [dbo].[Incidents]
(#SiteName varchar(200))
AS
SELECT SUM(COALESCE(i.Logged, 0)) AS LoggedIncidents
FROM tbl_Sites s
INNER JOIN tbl_Incidents i
ON s.Location = i.Location
WHERE s.Sites = #SiteName
AND i.[month] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0)
GROUP BY s.Sites
You could wrap the SELECT in another SELECT like so:
CREATE PROC [dbo].[Incidents]
(#SiteName varchar(200))
AS
SELECT COALESCE(TotalIncidents ,0)
FROM (
SELECT
(
SELECT SUM(i.Logged) as TotalIncidents
FROM tbl_Sites s
INNER JOIN tbl_Incidents i
ON s.Location = i.Location
WHERE s.Sites = #SiteName AND i.[month] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0)
GROUP BY s.Sites
) AS LoggedIncidents
)
Just ran into this problem, Kirtan's solution worked for me well, but the syntax was a little off. I did like this:
ISNULL(SUM(c.Logged), 0)
Post helped me solve my problem though so thanks to all.
The code you've posted above
SELECT SUM(ISNULL(c.Logged,0))
would not work due to wrong order
what would work is the following
SELECT ISNULL(SUM(c.Logged),0)
It evaulates the expression SUM then if it returns NULL it is replaced with 0.