Inserting "$" in a SELECT Statement SQL Server - sql

I have a SELECT Statement that shows details on Orders.
It uses the below code
SELECT Orders.OrderID, Orders.invoiceID, Items.itemName AS 'Item Name', Orders.quantity, DATENAME(mm, Orders.OrderDate) + ' ' + DATENAME(dd, Orders.OrderDate) + ', ' + DATENAME(yyyy, Orders.OrderDate) AS 'Order Date', (Orders.price * Orders.quantity) AS 'Total', Orders.delivered
FROM Orders
INNER JOIN Items
ON Orders.itemID = Items.itemID
ORDER BY Orders.orderID, Items.itemID ASC
Everything works fine, however I'm not sure how to get a "$" to show up to the left of the numbers in the "total" field.
All help will be appreciated.
Thanks,
Bryan

try this
SELECT Orders.OrderID,
Orders.invoiceID,
Items.itemName AS 'Item Name',
Orders.quantity,
DATENAME(mm, Orders.OrderDate) + ' ' + DATENAME(dd, Orders.OrderDate) + ', ' + DATENAME(yyyy, Orders.OrderDate) AS 'Order Date',
'$' + Convert(VARCHAR(50), Orders.price * Orders.quantity) AS 'Total',
Orders.delivered
FROM Orders
INNER JOIN Items ON Orders.itemID = Items.itemID
ORDER BY Orders.orderID, Items.itemID ASC

You could just explicitly concat it:
SELECT Orders.OrderID,
Orders.invoiceID,
Items.itemName AS 'Item Name',
Orders.quantity,
DATENAME(mm, Orders.OrderDate) + ' ' + DATENAME(dd, Orders.OrderDate) + ', ' + DATENAME(yyyy, Orders.OrderDate) AS 'Order Date',
'$' + (CAST (Orders.price * Orders.quantity) AS VARCHAR(100)) AS 'Total',
Orders.delivered
FROM Orders
INNER JOIN Items ON Orders.itemID = Items.itemID
ORDER BY Orders.orderID, Items.itemID ASC

This is untested, but this is the same answer but casting the numeric value.
SELECT Orders.OrderID,
Orders.invoiceID,
Items.itemName AS 'Item Name',
Orders.quantity,
DATENAME(mm, Orders.OrderDate) + ' ' + DATENAME(dd, Orders.OrderDate) + ', ' + DATENAME(yyyy, Orders.OrderDate) AS 'Order Date',
'$' + CAST((Orders.price * Orders.quantity) as varchar(90))
AS 'Total',
Orders.delivered
FROM Orders
INNER JOIN Items ON Orders.itemID = Items.itemID
ORDER BY Orders.orderID, Items.itemID ASC

Related

SQL Server : duplicate counts

I have the following. But in the final result some of the employee ID's are counted twice. My goal is to only count distinct employeeID for the [UniqueEmployees] column... Can someone please help me?
This is the code here:
IF OBJECT_ID(N'tempdb..#GG') IS NOT NULL
DROP TABLE #GG
SELECT DISTINCT
[month], vv.Hiremonth,
LoanNumber, vv.EmployeeId,
agentname,
vv.YearsOfService, vv.MonthsofService,
vv.TenureGrouping, vv.TenureMonthGrouping,
manager,
SUM([Call Counts]) as Calls,
SUM(opportunities) as Opportunities,
SUM([Discussed w/Customer]) as [Discussed w/Customer],
SUM(DidNotDiscuss) as [DidNotDiscuss],
SUM(CustomerInterested) as CustomerInterested,
(SELECT COUNT(DISTINCT MGR.EmployeeId)
FROM #MANAGERS MGR
WHERE --EmployeeId = EmployeeId
--and
CAST(CONVERT(datetime, RIGHT(MGR.HireMonth, 4) + LEFT(MGR.HireMonth, 2) + '01') as DATE) <= CAST(CONVERT(datetime, right([Month], 4) + left([Month], 2) + '01') as DATE)
--and MonthsOfService = MonthsOfService
--and YearsOfService = YearsOfService
) as UniqueEmployees
INTO
#GG
FROM
#FINALtemp2b VV
--left join
--(select distinct Employeeid
--from #FINALtemp2b) CC
--on CC.EmployeeId = VV.EmployeeId
GROUP BY
[month], vv.Hiremonth, LoanNumber, vv.EmployeeId,
agentname, vv.YearsOfService, vv.MonthsofService,
vv.TenureGrouping, vv.TenureMonthGrouping, manager
ORDER BY
[month]
Try removing the first 'distinct' and the excess 'select'.
IF OBJECT_ID(N'tempdb..#GG') is not null Drop Table #GG
select *
into #GG
from (
select
[month],
vv.Hiremonth,
LoanNumber,
vv.EmployeeId,
agentname,
vv.YearsOfService,
vv.MonthsofService,
vv.TenureGrouping,
vv.TenureMonthGrouping,
manager,
SUM([Call Counts]) as Calls,
sum(opportunities) as Opportunities,
sum([Discussed w/Customer]) as [Discussed w/Customer],
sum(DidNotDiscuss) as [DidNotDiscuss],
sum(CustomerInterested) as CustomerInterested,
count(distinct (MGR.EmployeeId))
from #MANAGERS MGR
where cast(convert(datetime,right(MGR.HireMonth,4) + left(MGR.HireMonth,2) + '01') as DATE) <= cast(convert(datetime,right([Month],4) + left([Month],2) + '01') as DATE)
group by
[month],
vv.Hiremonth,
LoanNumber,
vv.EmployeeId,
agentname,
vv.YearsOfService,
vv.MonthsofService,
vv.TenureGrouping,
vv.TenureMonthGrouping,
manager
) as UniqueEmployees

In IF statement with dates see whether a NULL exists

I have this query and i see if the AUD_CloseDate is > than todays date. Now i imagine these would be a NULL somewhere in AUD_CloseDate so in this statement i also want to check if there is a NULL value in AUD_CloseDate and if there is assign value 1900\01\01
SELECT ([Target Status] + '' + CAST(COUNT(*) AS NVARCHAR(255)) + ' of ' + CAST(#Total AS NVARCHAR(255))) AS TargetStatus, CAST(COUNT(*) AS FLOAT)/CAST(#Total AS FLOAT) AS [Count]
FROM (
SELECT CASE WHEN CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,t2.AUD_CloseDate), 101)) < CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,GETDATE()), 101))AND t1.[Status] in ('Open','Closed')
THEN 'Over Due: '
ELSE 'On Time: ' END AS [Target Status]
FROM #tmp1 t1 INNER JOIN dbo.Audit t2
ON t1.AUD_ID = t2.AUD_ID
WHERE t2.AUD_Deleted = 0
AND t2.AUD_LeadAuditor IN (SELECT ID FROM [dbo].[fx_SplitCommaSeperatedValues] (#LeadAssessor))
AND t2.AUD_Year = #Year
AND AUD_Quarter IN (SELECT ID FROM [dbo].[fx_SplitCommaSeperatedValues] (#Quarter)))DER
COALESCE is ANSI-compliant. Same syntax as ISNULL: COALESCE(t2.AUD_CloseDate,'19000101')
Why about a ISNULL() statement ?
ISNULL(t2.AUD_CloseDate,'19000101')
In you example :
SELECT ([Target Status] + '' + CAST(COUNT(*) AS NVARCHAR(255)) + ' of ' + CAST(#Total AS NVARCHAR(255))) AS TargetStatus, CAST(COUNT(*) AS FLOAT)/CAST(#Total AS FLOAT) AS [Count]
FROM (
SELECT CASE WHEN CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,ISNULL(t2.AUD_CloseDate,'19000101')), 101)) < CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,GETDATE()), 101))AND t1.[Status] in ('Open','Closed')
THEN 'Over Due: '
ELSE 'On Time: ' END AS [Target Status]
FROM #tmp1 t1 INNER JOIN dbo.Audit t2
ON t1.AUD_ID = t2.AUD_ID
WHERE t2.AUD_Deleted = 0
AND t2.AUD_LeadAuditor IN (SELECT ID FROM [dbo].[fx_SplitCommaSeperatedValues] (#LeadAssessor))
AND t2.AUD_Year = #Year
AND AUD_Quarter IN (SELECT ID FROM [dbo].[fx_SplitCommaSeperatedValues] (#Quarter)))DER
Use ISNULL function
ISNULL(AUD_CloseDate, '1900-01-01')
You are also:
adding 0 days to date
casting it to char(10)
, then casting again to date... Why?
You can achieve the same result withou these conversions, like this example:
SELECT
CASE
WHEN ISNULL(#a, '2014-01-29 13:50') < GETDATE()
THEN 'Over Due: '
ELSE 'On Time: '
END
Results 'Over due:'
SELECT
CASE
WHEN ISNULL(#a, '2014-01-29 15:00') < GETDATE()
THEN 'Over Due: '
ELSE 'On Time: '
END
Results 'On Time:'
** Now is 13:55 :)

T-SQL SUM Total

Below I have a T-SQL query that brings back amount of purchased items, less discounts and the total - grouped by month/year of purchase. How can I update the Query to return a Grand Total Row
where I would can add up the amounts in the Total Column?
It would be good to be able to add up all the rows but my
main item is I need to be able to get a grand total. Thanks.
Select DATENAME(month, [OrderDate]) + ' ' + CAST(YEAR(OrderDate) AS CHAR(4))
AS [Month],
SUM(Amount) AS [Amount],
SUM(Discount1) AS [Discount 1],
SUM(Discount2) AS [Discount 2],
SUM(Amount - Discount1 - Discount2) AS [Total]
From
Orders
JOIN Customer on orders.cust_ky=customer.cust_ky
GROUP BY DATENAME(month, [OrderDate]) + ' ' + CAST(YEAR(OrderDate) AS CHAR(4))
ORDER BY MAX(OrderDate)
Depending on your version of sql-server, you might be able to implement the rollup function (SQL-Server 2005+):
Select DATENAME(month, [OrderDate]) + ' ' + CAST(YEAR(OrderDate) AS CHAR(4)) AS [Month],
SUM(Amount) AS [Amount],
SUM(Discount1) AS [Discount 1],
SUM(Discount2) AS [Discount 2],
SUM(Amount - Discount1 - Discount2) AS [Total]
From Orders
JOIN Customer
on orders.cust_ky=customer.cust_ky
GROUP BY ROLLUP(DATENAME(month, [OrderDate]) + ' ' + CAST(YEAR(OrderDate) AS CHAR(4)))
ORDER BY MAX(OrderDate)
Or you can use a UNION ALL similar to this, where the second query gets the total without the GROUP BY:
Select DATENAME(month, [OrderDate]) + ' ' + CAST(YEAR(OrderDate) AS CHAR(4)) AS [Month],
SUM(Amount) AS [Amount],
SUM(Discount1) AS [Discount 1],
SUM(Discount2) AS [Discount 2],
SUM(Amount - Discount1 - Discount2) AS [Total]
From Orders
JOIN Customer
on orders.cust_ky=customer.cust_ky
GROUP BY DATENAME(month, [OrderDate]) + ' ' + CAST(YEAR(OrderDate) AS CHAR(4))
union all
Select 'Total',
SUM(Amount) AS [Amount],
SUM(Discount1) AS [Discount 1],
SUM(Discount2) AS [Discount 2],
SUM(Amount - Discount1 - Discount2) AS [Total]
From Orders
JOIN Customer
on orders.cust_ky=customer.cust_ky

SIMPLE SQL SELECT INTO GRAPH

I am having trouble outputting an SQL Select Statement to my XML to be used for my Graph
I have these results
December 2011 470 FRESENIUS
January 2012 434 FRESENIUS
February 2012 278 FRESENIUS
February 2012 2 STORESID
I need to output them like this so I can loop my Code and generate the XML
Month Year FRESNIUS STORESID
December 2011 470 0
January 2012 434 0
February 2012 278 2
take note i did not include the headers, these are all column results.
and also, STORESID and FRESNIUS are not STATIC Values. Multiple Storers Exists so I needed to Expand my number of Columns also , Dynamically.
I kinda need to output the second one to generate the XML properly thru PHP which I already have. Or are there any other proper way.
Thanks.
query below for the output i was talking about
SELECT
DATENAME(month, orderdate) + ' ' + CAST(Year(orderdate) AS VARCHAR(4)) AS 'Month Year' ,
count(*) 'Number of Orders',
storerkey
FROM orders
GROUP BY
storerkey,
DATENAME(month, orderdate) + ' ' + CAST(Year(orderdate) AS VARCHAR(4)),
CAST(Year(orderdate) AS VARCHAR(4)) + RIGHT('0' + CAST(Month(orderdate) AS VARCHAR(2)),2)
ORDER BY
storerkey,
CAST(Year(orderdate) AS VARCHAR(4)) + RIGHT('0' + CAST(Month(orderdate) AS VARCHAR(2)),2)
I am not 100% certain of the XML output you need but you can take advantage of SQL-Servers FOR XML clause and PIVOT function. This should get you started:
CREATE TABLE #Test (GraphDate DATETIME, Value INT, Type VARCHAR(50))
INSERT #Test VALUES
('01/12/2011', 470, 'FRESENIUS'),
('01/01/2012', 434, 'FRESENIUS'),
('01/12/2012', 278, 'FRESENIUS'),
('01/02/2012', 2, 'STORESID')
SELECT DATEPART(YEAR, GraphDate) [Year],
DATENAME(MONTH, GraphDate) [Month],
ISNULL(FRESENIUS, 0) [FRESENIUS],
ISNULL(STORESID, 0) [STORESID]
FROM #Test
PIVOT
( SUM(Value)
FOR Type IN ([FRESENIUS], [STORESID])
) PivotTable
FOR XML PATH('row'), ROOT
DROP TABLE #Test
EDIT
The below is the basic query you have asked for based on the query you have given.
SELECT DATENAME(MONTH, OrderDate) + ' ' + DATENAME(YEAR, OrderDate) [MonthYear],
ISNULL(FRESENIUS, 0) [FRESENIUS],
ISNULL(STORESID, 0) [STORESID]
FROM Orders
PIVOT
( COUNT(StorerKey)
FOR StorerKey IN ([FRESENIUS], [STORESID])
) PivotTable
ORDER BY DATEPART(YEAR, OrderDate), DATEPART(MONTH, OrderDate)
EDIT 2
I don't think PIVOT is supported by SQL-Server 2000. You will need to use aggregate functions:
SELECT DATENAME(MONTH, OrderDate) + ' ' + DATENAME(YEAR, OrderDate) [MonthYear],
COUNT(CASE WHEN StorerKey = 'FRESENIUS' THEN 1 END) [FRESENIUS],
COUNT(CASE WHEN StorerKey = 'STORESID' THEN 1 END) [STORESID]
FROM Orders
GROUP BY DATEPART(YEAR, OrderDate), DATEPART(MONTH, OrderDate), DATENAME(YEAR, OrderDate), DATENAME(MONTH, OrderDate)
ORDER BY DATEPART(YEAR, OrderDate), DATEPART(MONTH, OrderDate)
I think some FOR XML functionality is still available though so you may still be able to output your XML directly from SQL.
EDIT 3
DECLARE #SQL NVARCHAR(2000)
SELECT #SQL = ISNULL(#SQL, '') + ', COUNT(CASE WHEN StorerKey = ''' + StorerKey + ''' THEN 1 END) [' + StorerKey + ']'
FROM ( SELECT DISTINCT StorerKey
FROM Orders
) Keys
SET #SQL = 'SELECT DATENAME(MONTH, OrderDate) + '' '' + DATENAME(YEAR, OrderDate) [MonthYear]' + #SQL +
' FROM Orders
GROUP BY DATEPART(YEAR, OrderDate), DATEPART(MONTH, OrderDate), DATENAME(YEAR, OrderDate), DATENAME(MONTH, OrderDate)
ORDER BY DATEPART(YEAR, OrderDate), DATEPART(MONTH, OrderDate)'
EXECUTE SP_EXECUTESQL #SQL
You could join the table to itself. If I make assumptions about the column names, assume that either the FRESNIUS or STORESID could be absent, and use common table expressions (untested!):
WITH date_fresnius AS (
SELECT [Month Year], FRESNIUS
FROM original_table
)
, date_storesid AS (
SELECT [Month Year], STORESID
FROM original_table
)
SELECT
ISNULL( f.[Month Year], s.[Month Year]) AS [Month Year]
, ISNULL( f.FRESNIUS, 0 ) AS FRESNIUS
, ISNULL( s.STORESID, 0 ) AS STORESID
FROM
date_fresnius f
FULL OUTER JOIN date_storesid s ON (f.[Month Year] = s.[Month Year])
If you always have a FRESNIUS record you can use a LEFT JOIN instead.
Based on your query:
SELECT
DATENAME(MONTH, orderdate) + ' ' + CAST(YEAR(orderdate) AS VARCHAR(4)) AS [Month Year]
COUNT(CASE storerkey WHEN 'FRESNIUS' THEN 1 END) AS FRESNIUS,
COUNT(CASE storerkey WHEN 'STORESID' THEN 1 END) AS STORESID
FROM orders
GROUP BY YEAR(orderdate), MONTH(orderdate), DATENAME(MONTH, orderdate)
ORDER BY YEAR(orderdate), MONTH(orderdate)
Output:
Month Year FRESNIUS STORESID
December 2011 470 0
January 2012 434 0
February 2012 278 2

SQL: How to Group by Custom Year

For simplicities sake, I'll make up a similar example to what I have:
Let's say a db has a table of orders with an OrderDate field and a Company field. Then there's a table of Companies and each record has a YearEndingDate (which signifies that the year ends on that date each year, e.g. 6/6).
I need to add up all of the orders for each year.
I assume it would have to be something like this but I can't quite figure it out:
SELECT SUM(orderValue),
CASE WHEN orderDate <= YearEndingDate THEN DatePart(year, orderDate)
CASE WHEN orderDate > YearEndingDate THEN DatePart(year, orderDate) + 1
END as Year
FROM Orders
INNER JOIN Company ON Company.companyID = Order.companyID
GROUP By Company, Year
Any ideas?
Not sure what RDMS you are using but this should do the trick. The datepart and dateadd stuff are tsql specific but I'd assume you'd have access to similar functions on whatever platform you are using. The case in the where determines which year value to use.
Answer:
select c.companyid
,yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,1,o.orderdate))) as yearending
,sum(ordervalue) as numberoforders
from #orders o
join #companies c
on o.companyid = c.companyid
where orderdate between case when (cast(yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate)) as datetime) >= o.orderdate)
then yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,-1,o.orderdate)))
else yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate))
end
and
case when (cast(yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate)) as datetime) >= o.orderdate)
then yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate))
else yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,1,o.orderdate)))
end
group by c.companyid, o.orderdate, yearendingdate
Code to figure out problem:
declare #orders table (OrderDate datetime
,CompanyID varchar(20)
,OrderValue int)
insert into #orders
values (getdate(),'MS',2)
insert into #orders
values (DateAdd(year, -1, getdate()),'MS',3)
insert into #orders
values (DateAdd(year, -1, getdate()),'MS',1)
insert into #orders
values (DateAdd(year, 1, getdate()),'MS',4)
insert into #orders
values (DateAdd(year, 1, getdate()),'Blizzard',2)
insert into #orders
values (getdate(),'MS',11)
declare #companies table (CompanyID varchar(20)
,YearEndingDate varchar(20))
insert into #companies
values ('MS', '05/6')
insert into #companies
values ('Blizzard', '07/01')
select c.companyid
,o.orderdate
,yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate)) as sameyear
,yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,1,o.orderdate))) as plusyear
,yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,-1,o.orderdate))) as minusyear
from #orders o
join #companies c
on o.companyid = c.companyid
select c.companyid
,yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,1,o.orderdate))) as yearending
,sum(ordervalue) as numberoforders
from #orders o
join #companies c
on o.companyid = c.companyid
where orderdate between case when (cast(yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate)) as datetime) >= o.orderdate)
then yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,-1,o.orderdate)))
else yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate))
end
and
case when (cast(yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate)) as datetime) >= o.orderdate)
then yearendingdate + '/' + convert(varchar, datepart(yy, o.orderdate))
else yearendingdate + '/' + convert(varchar, datepart(yy, dateadd(yy,1,o.orderdate)))
end
group by c.companyid, o.orderdate, yearendingdate