Combining SQL Server Queries - sql

I am using SQL Server and I have two tables and I would like to combine into one query that I can use to fill a gridview.
Table1 dbo.Work
UID (PK, int)
Tech_Ticket (int)
RMA_Ticket (int)
Region (nchar10)
Completed (nchar10)
FA (nchar10)
Agent (nvarchar50)
Tracking (nvarchar50)
Date_Added (date)
Date_Updated (date)
Table2 dbo.Orders
UID (PK, int)
Order (int)
Agent (nvarchar50)
Ticket (int)
Notes (nvarchar50)
Right now I have them setup as two separate queries and two separate tables.
Query1:
SELECT [Agent],
SUM(CASE WHEN [Date_Added] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'New ',
SUM(CASE WHEN [Date_Updated] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'Worked',
SUM(CASE WHEN [Completed] = 'yes' AND [Date_Updated] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'Completed',
SUM(CASE WHEN [Failure_Analysis] = 'yes' AND [Date_Updated] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'FA'
FROM Work
GROUP BY [Agent]
Query2:
SELECT [Agent]
SUM(CASE WHEN [Date] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'Orders'
FROM Orders
GROUP BY [Agent]
Is there a way to combine these two queries into one?

You can JOIN them. Assuming that Work is the main table, it should be like this:
SELECT A.*, B.Orders
FROM ( SELECT [Agent],
SUM(CASE WHEN [Date_Added] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'New',
SUM(CASE WHEN [Date_Updated] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'Worked',
SUM(CASE WHEN [Completed] = 'yes' AND [Date_Updated] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'Completed',
SUM(CASE WHEN [Failure_Analysis] = 'yes' AND [Date_Updated] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'FA'
FROM Work
GROUP BY [Agent]) A
LEFT JOIN (SELECT [Agent]
SUM(CASE WHEN [Date] BETWEEN #startDate AND #endDate THEN 1 ELSE 0 END) AS 'Orders'
FROM Orders
GROUP BY [Agent]) B
ON A.[Agent] = B.[Agent]

Related

Combine multiple queries in 1 return row

I have a query which should return 1 row for each DetectorID. What we currently have is the following:
DECLARE #StartDate datetime SET #StartDate = '2017-12-01 00:00'
DECLARE #EndDate datetime select #EndDate ='2018-01-01 00:00'
DECLARE #Limit1 real SET #Limit1 = 200; DECLARE #AssenLimit1 real SET #AssenLimit1 = 0;
DECLARE #Limit2 real SET #Limit2 = 300; DECLARE #AssenLimit2 real SET #AssenLimit2 = 0;
DECLARE #Limit3 real SET #Limit3 = 350; DECLARE #AssenLimit3 real SET #AssenLimit3 = 0;
DECLARE #Limit4 real SET #Limit4 = 400; DECLARE #AssenLimit4 real SET #AssenLimit4 = 0;
DECLARE #Limit5 real set #Limit5 = 500; DECLARE #AssenLimit5 real SET #AssenLimit5 = 0;
SELECT DetectorID, AVG(ValidWIM) AS 'PI_mean_WIM',
COUNT(ValidWIM) AS 'PI_mean_WIM2',
COUNT(CASE
WHEN ValidWIM > 0.5 THEN ValidWIM ELSE NULL END)
AS 'PI_mean_WIM3'
,AVG((ValidWDD_Left+ValidWDD_Right)/2) AS 'PI_mean_WDD'
,COUNT(ValidWDD_Left) AS 'PI_mean_WDD2'
,COUNT (CASE
WHEN (ValidWDD_Left>0.5 AND ValidWDD_Right>0.5) THEN ValidWDD_Left ELSE NULL END)
AS PI_mean_WDD3
,COUNT(CASE
WHEN AxleLoad IS NOT NULL Then TrainPassageInformationID ELSE NULL END)
AS 'nWheels'
, COUNT(CASE
WHEN (PeakForceLeft > #Limit1 OR PeakForceRight>#Limit1) THEN TrainPassageInformationID ELSE NULL END)
AS 'n>200'
, COUNT(CASE
WHEN (PeakForceLeft > #Limit2 OR PeakForceRight>#Limit2) THEN TrainPassageInformationID ELSE NULL END)
AS 'n>300'
, COUNT(CASE
WHEN (PeakForceLeft > #Limit3 OR PeakForceRight>#Limit3) THEN TrainPassageInformationID ELSE NULL END)
AS 'n>350'
, COUNT(CASE
WHEN (PeakForceLeft > #Limit4 OR PeakForceRight>#Limit4) THEN TrainPassageInformationID ELSE NULL END)
AS 'n>400'
, COUNT(CASE
WHEN (PeakForceLeft > #Limit5 OR PeakForceRight>#Limit5) THEN TrainPassageInformationID ELSE NULL END)
AS 'n>500'
From WheelDamage
where (TimeOfAxle > #StartDate AND TimeOfAxle < #EndDate) and DetectorID in (11,12)
GROUP BY DetectorID
order by DetectorID asc
SELECT DetectorID,
AVG(PeakForceLeft) AS 'NoiseLeft' FROM WheelDamage as t
where PeakForceLeft in (
select top 10 percent PeakForceLeft
from wheeldamage as tt
where tt.WheelDamageID = t.WheelDamageID AND tt.PeakForceLeft <> 0 AND tt.PeakForceLeft IS NOT NULL AND (t.TimeOfAxle > #StartDate AND t.TimeOfAxle < #EndDate)
order by tt.PeakForceLeft asc)
Group By DetectorID
order by DetectorID asc
SELECT DetectorID,
AVG(PeakForceRight) AS 'NoiseRight' FROM WheelDamage as t
where PeakForceLeft in (
select top 10 percent PeakForceRight
from wheeldamage as tt
where tt.WheelDamageID = t.WheelDamageID AND tt.PeakForceRight <> 0 AND tt.PeakForceLeft IS NOT NULL AND (t.TimeOfAxle > #StartDate AND t.TimeOfAxle < #EndDate)
order by tt.PeakForceLeft asc)
Group By DetectorID
order by DetectorID asc
SELECT DetectorId, COUNT (DateTime) AS 'Tags1'
FROM [TagPassage]
WHERE Valid = 1 AND (DateTime > #StartDate AND DateTime < #EndDate)
GROUP by DetectorID
Order by DetectorID asc
SELECT DetectorID, COUNT(CASE
WHEN (TotalWeight=0 OR TotalWeight IS NULL) AND (HasTrainStandStill<>1 OR HasTrainStandStill IS NULL) THEN (TrainPassageInformationID) ELSE NULL END) AS 'notAnalyzed'
, SUM (TotalWeight) AS 'TotalWeight'
FROM TrainPassageInformation
WHERE (Datetime > #StartDate AND Datetime < #EndDate)
Group By DetectorID
order by DetectorID asc
This is returing 5 new rows which I understand. This is because i have 5 select statements. However, I need to know how i can put the bottom 4 select statements in the top one so that it will only return 1 row.
I have tried with Select(Select X xxx). But that gave the error that it is returning more then 1 rows.
The image above is showing the current result. I want the bottom 4 tables to be columns in the first table.
can you just join/left join all the scripts together as table and link by DetectorID, then u can select the columns from the 4 scripts at the bottom to the right.

Query with Join of tables is taking long time to execute 5 min

SELECT
B.AccountBranchID
,B.VoucherNo
,B.BranchName AS BranchName
,B.InvoiceNo
,CONVERT(VARCHAR, B.InvoiceDate, 103) AS InvoiceDate
,CONVERT(VARCHAR, B.VoucherDate, 103) AS VoucherDate
,B.CustomerName
,B.RefID
,LN.AccountName AS LedgerName
,b.SalesPersonName AS SalesPersonName
,LN.LedgerCode
,B.AgentName
,B.ShipperName
,B.Segment
,B.TransactionType
,B.JobNo
,CONVERT(VARCHAR, B.JOBDate, 103) AS JOBDate
,B.MAWBNo
,B.HAWBNo
,B.AccountName
,B.LedgerCode AS AccountLedgerCode
,B.CurrencyCode
,ISNULL(B.Amount, 0) AS Amount
,B.ChargeExRate
,(CASE B.CRDR
WHEN 'CR' THEN (B.ChargeBaseAmount * -1)
ELSE B.ChargeBaseAmount
END) AS ChargeBaseAmount
,(CASE B.CRDR
WHEN 'CR' THEN 'Credit'
ELSE 'Debit'
END) AS CRDR
FROM VW_VoucherTR AS B
INNER JOIN VW_VoucherTR AS LN
ON B.VoucherID = LN.VoucherID
WHERE B.CompanyID = #CompanyID
AND (CASE #Type
WHEN 'I' THEN B.InvoiceDate
ELSE B.VoucherDate
END) BETWEEN ISNULL(#FromDate, (SELECT
FYearStart
FROM Secmst_FinancialYear
WHERE FyearId = #yearID)
) AND ISNULL(#ToDate, GETDATE())
AND (#Segment IS NULL
OR B.Segment = #Segment)
AND (#BranchMappingID IS NULL
OR B.BranchMappingID = #BranchMappingID)
AND B.VoucherTypeCode IN ('sv')
AND B.IsDeleted = 0
AND (B.GroupName <> 'Sundry Creditors'
AND B.GroupName <> 'Sundry Debtors')
AND LN.GroupName IN ('Sundry Debtors', 'Sundry Creditors')
The subquery in the BETWEEN is probably what is killing you. Have you looked at the execution plan?
BETWEEN ISNULL(#FromDate, (
SELECT FYearStart
FROM Secmst_FinancialYear
WHERE FyearId = #yearID
))
AND ISNULL(#ToDate, GETDATE())
What's happening is you are running that query across every row, and by my looks, that's unnecessary because you are only needing static dates there (not anything based on the joined rows.)
Try this:
DECLARE #FromDateActual datetime = ISNULL(#FromDate, (
SELECT FYearStart
FROM Secmst_FinancialYear
WHERE FyearId = #yearID
));
DECLARE #ToDateActual datetime = ISNULL(#ToDate, GETDATE());
SELECT B.AccountBranchID
,B.VoucherNo
,B.BranchName AS BranchName
,B.InvoiceNo
,convert(VARCHAR, B.InvoiceDate, 103) AS InvoiceDate
,convert(VARCHAR, B.VoucherDate, 103) AS VoucherDate
,B.CustomerName
,B.RefID
,LN.AccountName AS LedgerName
,b.SalesPersonName AS SalesPersonName
,LN.LedgerCode
,B.AgentName
,B.ShipperName
,B.Segment
,B.TransactionType
,B.JobNo
,convert(VARCHAR, B.JOBDate, 103) AS JOBDate
,B.MAWBNo
,B.HAWBNo
,B.AccountName
,B.LedgerCode AS AccountLedgerCode
,B.CurrencyCode
,ISNULL(B.Amount, 0) AS Amount
,B.ChargeExRate
,(
CASE B.CRDR
WHEN 'CR'
THEN (B.ChargeBaseAmount * - 1)
ELSE B.ChargeBaseAmount
END
) AS ChargeBaseAmount
,(
CASE B.CRDR
WHEN 'CR'
THEN 'Credit'
ELSE 'Debit'
END
) AS CRDR
FROM VW_VoucherTR AS B
INNER JOIN VW_VoucherTR AS LN ON B.VoucherID = LN.VoucherID
WHERE B.CompanyID = #CompanyID
AND (
CASE #Type
WHEN 'I'
THEN B.InvoiceDate
ELSE B.VoucherDate
END
) BETWEEN #FromDateActual
AND #ToDateActual
AND (
#Segment IS NULL
OR B.Segment = #Segment
)
AND (
#BranchMappingID IS NULL
OR B.BranchMappingID = #BranchMappingID
)
AND B.VoucherTypeCode IN ('sv')
AND B.IsDeleted = 0
AND (
B.GroupName <> 'Sundry Creditors'
AND B.GroupName <> 'Sundry Debtors'
)
AND LN.GroupName IN (
'Sundry Debtors'
,'Sundry Creditors'
)
Beyond that you could consider adding non-clustered indexes. The Query Analyzer may even suggest a couple. But you'll want to be careful there, depending on how the data is used and loaded, as too many indexes or large ones can lead to further performance issues in other places (row insertions, page fragmentation, etc).
There could be many reasons for it, but one thing is quite plain. The following part is not sargable.
(CASE #Type
WHEN 'I' THEN B.InvoiceDate
ELSE B.VoucherDate
END) BETWEEN ISNULL(#FromDate, (SELECT
FYearStart
FROM Secmst_FinancialYear
WHERE FyearId = #yearID)
) AND ISNULL(#ToDate, GETDATE())
Should be rewritten to be sargable, so that indexes can be used.
SELECT #FromDate = ISNULL(#FromDate, (SELECT
TOP 1 FYearStart
FROM Secmst_FinancialYear
WHERE FyearId = #yearID)) )
SELECT #ToDate = ISNULL(#ToDate, GETDATE())
SELECT
...
WHERE
...
AND
((#Type='I' AND B.InvoiceDate BETWEEN #FromDate AND #ToDate)
OR
(#Type<>'I' AND B.VoucherDate BETWEEN #FromDate AND #ToDate))
AND
...
Of course proper indexing is the way how to speed up your query, if no indexes are on InvoiceDate, VoucherDate, etc. then your query will use full table scan instead of index seek and it will be slow.

Improve SQL Server query

I have to improve this query, that works very well.
DECLARE #timTimeout int,
#iniDate varchar(20),
#endDate varchar(20)
SET #iniDate = '2014-07-20 00:00:00'
SET #endDate = '2014-11-24 23:59:59'
SET #timTimeout = 4000
SET ANSI_WARNINGS OFF
SELECT
'Approved (0200)' = ISNULL(SUM(CASE CodMsgIncome WHEN '0200' THEN 1 END), 0),
'Approved Off (0220)' = ISNULL(SUM(CASE CodMsgIncome WHEN '0220' THEN 1 END), 0),
'Cancel (0400)' = ISNULL(SUM(CASE CodMsgIncome WHEN '0400' THEN 1 END), 0),
'Regret (0420)' = ISNULL(SUM(CASE CodMsgIncome WHEN '0420' THEN 1 END), 0),
'TOTAL' = COUNT(*),
'Time-outs' = ISNULL(SUM(CASE WHEN DATEDIFF(ms, DateMsgIncome, DateMsgSent) > #timTimeout THEN 1 END), 0),
'Disponibility (%)' = (1 - CAST(ISNULL(SUM(CASE WHEN DATEDIFF(ms, DateMsgIncome, DateMsgSent) > #timTimeout THEN 1 END), 0) as money) / COUNT(*)) * 100
FROM Message (NOLOCK)
WHERE DateMsgIncome BETWEEN #iniDate AND #endDate
AND CodMsgIncome IN ('0200', '0220', '0400', '0420', '0800', '0900', '9080', '9085')
AND DescMsgIncome <> '0220'
Now, I have to prepare a report with Total data organized by month.
The output disered seems like this:
Approved (0200) | Approved Off (0220) | Cancel | Total | Time-outs | Disponibility (%)
July | 35 15 12 62 0 100.00
.
.
.
EDIT:
It is only one table on my query.
Table Message:
DateMsgIncome date,
DateMsgSent date,
CodMsgIncome varchar(4),
DescMsgIncome varchar(4),
CodMsgAnswer int.
Any suggestion is welcome.
Thanks in advance.
I ran your query through a code formatter to help clean it up. I also change the variable declaration since you didn't seem to understand what I was saying. For the record, the way you had it coded you might have missed some rows in the last few milliseconds of the day.
I changed the DATEDIFF function to use the datepart name spelled out because it is just too easy use the wrong abbreviation and get it wrong. I also simplified the calculation for the last column. The cast to money was not needed if you change the 1 - to 1.0 -. You should avoid using reserved words for object names and avoid spaces in column names. Let the front end do this kind of pretty formatting.
I also added the soon the be required WITH keyword when using table hints. (I would recommend understand what NOLOCK really means before using it).
DECLARE #timTimeout int
, #iniDate date
, #endDate date
SET #iniDate = '2014-07-20'
SET #endDate = '2014-11-25'
SET #timTimeout = 4000
SELECT MONTH(DateMsgIncome) as MyMonthColumn
, 'Approved (0200)' = ISNULL(SUM(CASE CodMsgIncome WHEN '0200' THEN 1 END), 0)
, 'Approved Off (0220)' = ISNULL(SUM(CASE CodMsgIncome WHEN '0220' THEN 1 END), 0)
, 'Cancel (0400)' = ISNULL(SUM(CASE CodMsgIncome WHEN '0400' THEN 1 END), 0)
, 'Regret (0420)' = ISNULL(SUM(CASE CodMsgIncome WHEN '0420' THEN 1 END), 0)
, 'TOTAL' = COUNT(*)
, 'Time-outs' = ISNULL(SUM(CASE WHEN DATEDIFF(MILLISECOND, DateMsgIncome, DateMsgSent) > #timTimeout THEN 1 END), 0)
, 'Disponibility (%)' = (1.0 - ISNULL(SUM(CASE WHEN DATEDIFF(MILLISECOND, DateMsgIncome, DateMsgSent) > #timTimeout THEN 1 END), 0) / COUNT(*)) * 100
FROM [Message] WITH (NOLOCK) --Ack!!! I wouldn't let this fly on my system due to inconsistencies with this hint unless accuracy is not important (like
WHERE DateMsgIncome >= #iniDate
AND DateMsgIncome < #endDate
AND CodMsgIncome IN
(
'0200'
, '0220'
, '0400'
, '0420'
, '0800'
, '0900'
, '9080'
, '9085'
)
AND DescMsgIncome <> '0220'
GROUP BY MONTH(DateMsgIncome)

Join multiple queries with different search criteria

I have 4 queries that are identical with the exception of one of the criteria clauses at the end. I am trying to find a way to condense these 4 into 1, if possible. Currently, a program that we wrote calls these 4 statements through 4 stored procedures, but if I can make that 1 call that returns all 4, that would be great. Here's the bulk of the statement:
SELECT SUM(PausedTime) AS PausedMode
FROM UsageStats
WHERE StartDate >= CONVERT(VARCHAR(8), #StartDate, 112) AND StopDate < CONVERT(VARCHAR(8), #EndDate, 112)
AND LocationID = #LocationID
AND SystemID = #SystemID
AND PlayingArea = #PlayingArea
AND PausedTime > 0
I have 3 more of these and the only thing that changes is the field in the SUM calculation (all SUM fields are of type int):
SUM(PlayModeTime) AS PlayModeTime
SUM(RecordModeTime) AS RecordModeTime
SUM(ReplayModeTime) AS ReplayModeTime
and the last AND criteria
AND PlayModeTime > 0
AND RecordModeTime > 0
AND ReplayModeTime > 0
I tried using the CASE statement in the select clause but it failed:
SELECT
playMode = (CASE WHEN PlayModeTime > 0 THEN SUM(PlayModeTime) END),
pausedMode = (CASE WHEN PausedTime > 0 THEN SUM(PausedTime) END),
recordMode = (CASE WHEN RecordModeTime > 0 THEN SUM(RecordModeTime) END),
replayMode = (CASE WHEN ReplayModeTime > 0 THEN SUM(ReplayModeTime) END)
FROM UsageStats
WHERE StartDate >= CONVERT(VARCHAR(8), #StartDate, 112) AND StopDate < CONVERT(VARCHAR(8), #EndDate, 112)
AND LocationID = #LocationID
AND SystemID = #SystemID
AND PlayingArea = #PlayingArea
GROUP BY PlayModeTime, PausedTime, RecordModeTime, ReplayModeTime
I'd like to get something like this:
PlayModeTime | PausedMode | RecordModeTime | ReplayModeTime
---------------------------------------------------------------
200 340 10 55
Any help is appreciated.
I don't see why you need those conditions at all, since SUM will add zero when the value is 0. Can't you just SUM all of your columns?:
SELECT
playMode = SUM(PlayModeTime),
pausedMode = SUM(PausedTime),
recordMode = SUM(RecordModeTime),
replayMode = SUM(ReplayModeTime)
FROM UsageStats
WHERE StartDate >= CONVERT(VARCHAR(8), #StartDate, 112)
AND StopDate < CONVERT(VARCHAR(8), #EndDate, 112)
AND LocationID = #LocationID
AND SystemID = #SystemID
AND PlayingArea = #PlayingArea
You need to move the sum outside of the case statement:
SELECT
playMode = SUM(CASE WHEN PlayModeTime > 0 THEN PlayModeTime ELSE 0 END),
pausedMode = SUM(CASE WHEN PausedTime > 0 THEN PausedTime ELSE 0 END),
recordMode = SUM(CASE WHEN RecordModeTime > 0 THEN RecordModeTime ELSE 0 END),
replayMode = SUM(CASE WHEN ReplayModeTime > 0 THEN ReplayModeTime ELSE 0 END)
FROM UsageStats
WHERE StartDate >= CONVERT(VARCHAR(8), #StartDate, 112) AND StopDate < CONVERT(VARCHAR(8), #EndDate, 112)
AND LocationID = #LocationID
AND SystemID = #SystemID
AND PlayingArea = #PlayingArea
GROUP BY PlayModeTime, PausedTime, RecordModeTime, ReplayModeTime
The reason is that the case will be evaluated for each row. In your example, you're taking the sum of the column, but only for that row.
This only differs from Lamak's answer above in that it will treat negative values as zeroes in the sum.

Transform multiple queries into single row

I have a report that I would like to base on a single SQL statement. The problem is the data is based on several SQL statements. For example.
SELECT COUNT(*) as 'Cases Opened'
FROM tblCases
WHERE DateAssigned BETWEEN #StartDate AND #EndDate
SELECT COUNT(*) as 'Cases Closed'
FROM tblCases
WHERE ClosedDate BETWEEN #StartDate AND #EndDate
SELECT COUNT(*) as 'Tickets Issued'
FROM tblTicket
WHERE DateIssued BETWEEN #StartDate AND #EndDate
SELECT COUNT(*) as 'Warnings Issued'
FROM tblWarning
WHERE DateIssued BETWEEN #StartDate AND #EndDate
Is there a way to turn these four seperate SQL statements into a single SQL statement such that each result is listed as a column? For example ..
Cases Opened Cases Closed Tickets Issued Warnings Issued
******************************************************************************
256 | 165 | 56 | 165
EDIT I am using SQL Server and no there is no relationship between the tables.
select
(
SELECT COUNT(*)
FROM tblCases
WHERE DateAssigned BETWEEN #StartDate AND #EndDate
) as 'Cases Opened' ,
(SELECT COUNT(*)
FROM tblCases
WHERE ClosedDate BETWEEN #StartDate AND #EndDate
) as 'Cases Closed' ,
(SELECT COUNT(*)
FROM tblTicket
WHERE DateIssued BETWEEN #StartDate AND #EndDate
) as 'Tickets Issued' ,
(SELECT COUNT(*)
FROM tblWarning
WHERE DateIssued BETWEEN #StartDate AND #EndDate
) as 'Warnings Issued'
from dual
from dual would be necessary in oracle, mysql supports it but is not necessary and I'm not sure about sqlserver since I don't have one in front of me.
You could union and pivot the data, like so:
SELECT SUM(CASE WHEN FieldName='Cases Opened' THEN Value ELSE 0 END) AS Cases_Opened,
SUM(CASE WHEN FieldName='Cases Closed' THEN Value ELSE 0 END AS Cases_Closed,
SUM(CASE WHEN FieldName='Warning Issued' THEN Value ELSE 0 END) AS Warnings_Issued,
SUM(CASE WHEN FieldName='Tickets Issued' THEN Value ELSE 0 END) AS Tickets_Issued
FROM
(
SELECT COUNT(*) as Value, 'Cases Opened' as FieldName
FROM tblCases
WHERE DateAssigned BETWEEN #StartDate AND #EndDate
UNION
SELECT COUNT(*) as Value, 'Cases Closed' as FieldName
FROM tblCases
WHERE ClosedDate BETWEEN #StartDate AND #EndDate
UNION
SELECT COUNT(*) as Value, 'Tickets Issued' as FieldName
FROM tblTicket
WHERE DateIssued BETWEEN #StartDate AND #EndDate
UNION
SELECT COUNT(*) as Value, 'Warnings Issued' as FieldName
FROM tblWarning
WHERE DateIssued BETWEEN #StartDate AND #EndDate
)
Check out the pivot statement if you are running in SQLServer