Combine two query and display in single line - sql-server

I am using the below code to find the sales by credit card and cash and the current output show as below but I want to get the card and cash sales in single line.
current output:
expected output:
SELECT CONVERT(VARCHAR(10), CreateDate, 103) DT,SUM(AMOUNT),NULL FROM JnlDetails WHERE JnlDetails.CreateDate > '2021-05-01'
AND ACCOUNTID = '000153200101'
GROUP BY CONVERT(VARCHAR(10), CreateDate, 103)
UNION ALL
SELECT CONVERT(VARCHAR(10), CreateDate, 103) DT,NULL,SUM(AMOUNT) FROM JnlDetails WHERE JnlDetails.CreateDate > '2021-05-01'
AND ACCOUNTID = '000153200201'
GROUP BY CONVERT(VARCHAR(10), CreateDate, 103)
ORDER BY DT
Is there any other option available to achieve this without Union? Both the information's (Card and Sales) in the same table, based on the accountid we can split.

Using a case expression you can conditionally sum your values
select Convert(varchar(10), CreateDate, 103) DT,
Sum (case when ACCOUNTID = '000153200101' then AMOUNT end) as Cash,
Sum (case when ACCOUNTID = '000153200201' then AMOUNT end) as Card
from JnlDetails
where JnlDetails.CreateDate > '2021-05-01'
and ACCOUNTID in ('000153200101','000153200201')
group by Convert(varchar(10), CreateDate, 103)

Related

Temptable in SQL Server

Query #1:
SELECT a.*
INTO #TempTable1
FROM
(SELECT
Vendor,
CASE WHEN CONVERT(varchar(50), DateModified, 101)='01/01/1900' THEN '' ELSE CONVERT(varchar(50), DateModified, 101) END AS 'Date of Last Check',
CASE WHEN CONVERT(varchar(50), PaycommissionDate, 101)='01/01/1900' THEN '' ELSE CONVERT(varchar(50), PaycommissionDate, 101) END AS 'Date of check for month',
SUM([Original $ Total]) 'Amount'
FROM
Tbl_Commission_Reconcilation
WHERE
Vendor IS NOT NULL
AND MONTH([Order Date]) = MONTH (GETDATE())
GROUP BY
Tbl_Commission_Reconcilation.Vendor,
CONVERT(varchar(50), DateModified, 101),
[Sales Rep], PaycommissionDate) a
Output:
Vendor Date of Last Check Date of check for month Amount
-----------------------------------------------------------------------------
Boston Warehouse 12/12/2017 12/12/2017 919.00
Woodlink 12/12/2017 12/12/2017 979.86
Query #2:
SELECT b.*
INTO #TempTable2
FROM
(SELECT
[Sales Rep],
SUM([Commission $ paid]) 'Commission $ paid'
FROM
Tbl_Commission_Reconcilation
WHERE
Vendor IS NOT NULL
AND MONTH([Order Date]) = MONTH (GETDATE())
GROUP BY
[Sales Rep]) b
Output 2:
Sales Rep Commission $ paid
---------------------------------
Tammy Hanson 379.77
Final query:
select *
from #TempTable1, #TempTable2
Final output:
Vendor DateofLastCheck Dateofcheckformonth Amount Sales Rep Commpaid
Boston
Warehouse 12/12/2017 12/12/2017 919.00 Tammy Hanson 379.77
Woodlink 12/12/2017 12/12/2017 979.86 Tammy Hanson 379.77
Output 2 shows only one commission paid 379.77 for Tammy Hanson.But in final output shows 2 times commission paid 379.77.How to rectify this problem?
How to show only one commission paid in the final output?Please, any one helps me.
You are getting the duplicate values because you are using a Cross Join ( Cartesian Product) here. Please specify at least 1 condition to match the records from both tables so that the values will be displayed only against the desired records.
As per your current query, it will return all the possible combinations of rows in both tables. change it like this
select * from #TempTable1 T1,#TempTable2 T2 WHERE T1.ColumnName = T2.ColumnName
or you can also say
select * from #TempTable1 T1
inner join #TempTable2 T2
WHERE T1.ColumnName = T2.ColumnName
-- if you want records that have matches on both tables
or
select * from #TempTable1 T1
left join #TempTable2 T2
WHERE T1.ColumnName = T2.ColumnName
-- if you want records from #TempTable1 and display null for TempTable2 if no matching records
It appears you can just do one query. The larger query already has [sales rep] in the group by clause, so why not just sum the commission?
SELECT
a.* INTO #TempTable1
FROM (
SELECT
Vendor
, CASE WHEN CONVERT(varchar(50), DateModified, 101) = '01/01/1900' THEN '' ELSE CONVERT(varchar(50), DateModified, 101) END
AS 'Date of Last Check'
, CASE WHEN CONVERT(varchar(50), PaycommissionDate, 101) = '01/01/1900' THEN '' ELSE CONVERT(varchar(50), PaycommissionDate, 101) END
AS 'Date of check for month'
, SUM([Original $ Total]) 'Amount'
, [Sales Rep]
, SUM([Commission $ paid]) 'Commission $ paid'
FROM Tbl_Commission_Reconcilation
WHERE Vendor IS NOT NULL
AND MONTH([Order Date]) = MONTH(GETDATE())
GROUP BY
Tbl_Commission_Reconcilation.Vendor
, CONVERT(varchar(50), DateModified, 101)
, [Sales Rep]
, PaycommissionDate
) a
You should also add row_number to your queries
For Table1
SELECT a.*
INTO #TempTable1
FROM
(SELECT
Vendor,
CASE WHEN CONVERT(varchar(50), DateModified, 101)='01/01/1900' THEN '' ELSE CONVERT(varchar(50), DateModified, 101) END AS 'Date of Last Check',
CASE WHEN CONVERT(varchar(50), PaycommissionDate, 101)='01/01/1900' THEN '' ELSE CONVERT(varchar(50), PaycommissionDate, 101) END AS 'Date of check for month',
SUM([Original $ Total]) 'Amount',
ROW_NUMBER() OVER(ORDER BY Vendor, DateModified, [Sales Rep]) RN
FROM
Tbl_Commission_Reconcilation
WHERE
Vendor IS NOT NULL
AND MONTH([Order Date]) = MONTH (GETDATE())
GROUP BY
Tbl_Commission_Reconcilation.Vendor,
CONVERT(varchar(50), DateModified, 101),
[Sales Rep], PaycommissionDate) a
For Table 2
SELECT b.* INTO #TempTable2
from
(SELECT [Sales Rep],SUM([Commission $ paid]) 'Commission $ paid',
ROW_NUMBER() OVER(ORDER BY [Sales Rep]) RN
from Tbl_Commission_Reconcilation where Vendor is not null and Month([Order Date])= MONTH (Getdate())
group by [Sales Rep])b
and also left join table1 and table2 with this RN column
select
*
from #TempTable1 t1
LEFT JOIN #TempTable2 t2
ON t1.RN = t2.RN

Check order row depending on result query in sql server

I have a table checks2:
AllTaskNo int,
CheckQuosimaNo int,
Masroof numeric(18,3),
Maqbood numeric(18,3),
Date1 smalldatetime
I have a query to get balance:
SELECT
AllTaskNo
,CheckQuosimaNo
,Masroof
,Maqbood
,Date
,(SELECT 0 + SUM(Maqbood - Masroof) AS Expr1
FROM Checks2 AS t2
WHERE (BankNo = 6)
AND (CheckQuosimaNo <= Checks2.CheckQuosimaNo)
AND (Date1 BETWEEN CONVERT(DATETIME, '01/01/2014', 103)
AND CONVERT(DATETIME, '31/10/2015', 103)) AND AllTaskNo
IN (SELECT No
FROM AllTasks
WHERE (BankNo = 6)
AND (Date BETWEEN CONVERT(DATETIME, '01/01/2014', 103)
AND CONVERT(DATETIME, '31/10/2015', 103))))) AS NetAmount
FROM
Checks2
WHERE
(BankNo = 6)
AND
(Date1 BETWEEN CONVERT(DATETIME, '01/01/2014', 103)
AND CONVERT(DATETIME, '31/10/2015', 103))
ORDER BY
BankNo
,Date1
,CheckQuosimaNo
the result is:
enter image description here
I need to make a formula (like excel for example NetAmount = NetAmount before + Maqbood - Masroof)
I expect that the selected row in NetAmount = 656360 but then query produce NetAmount=5567675.976
How can I fix this problem
There are many way to do this like Over and Correlated Sub Queries
Over:
SELECT
AllTaskNo ,Maqbood , Masroof,
SUM(-1*Maqbood +Masroof) OVER (ORDER BY AllTaskNo ) AS NetAmount
FROM Checks2 T1
Correlated Sub Queries (Need Sql server 2014+)
SELECT
AllTaskNo ,Maqbood , Masroof,
(
SELECT
SUM(-1*Maqbood +Masroof)
FROM Checks2 T2
WHERE T2.AllTaskNo <=T1.AllTaskNo
) AS NetAmount FROM Checks2 T1
Feel free to comment if you need any further assistance on this item
I have been solve my problem by my own solution ... I think there is a shorter solution .. but any way I get what I want... My solution is:
1- Make a table (Checks3) with a new field named (rank) which is the correct order of the command result.
2- Create a new command mostly like the first one containing the (bank balance formula).
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Checks3]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[Checks3]
SELECT Checks2.BankNo, Checks2.AllTaskNo, Checks2.CheckQuosimaNo, Checks2.Masroof, Checks2.Maqbood, Checks2.Date1, rank() OVER (ORDER BY checks2.date1, checks2.CheckQuosimaNo) as rank
INTO Checks3
FROM Checks2 INNER JOIN
AllTasks ON Checks2.AllTaskNo = AllTasks.No where Checks2.BankNo =6 and (Checks2.[Date1] BETWEEN CONVERT(DATETIME, '01/10/2015', 103) AND CONVERT(DATETIME,'31/10/2015', 103)) ORDER BY CHECKS2.BankNo, CHECKS2.CheckQuosimaNo
SELECT Checks3.AllTaskNo, Checks3.CheckQuosimaNo, Checks3.Masroof, Checks3.Maqbood, Checks3.Date1,
( SELECT 0+SUM(t2.Maqbood - t2.Masroof) FROM Checks3 t2
WHERE t2.BankNo =6 and t2.rank <= Checks3.rank
and (t2.[Date1] BETWEEN CONVERT(DATETIME, '01/10/2014', 103) AND CONVERT(DATETIME,'31/10/2015', 103))
) as NetAmount
FROM Checks3
where Checks3.BankNo =6 and (Checks3.[Date1] BETWEEN CONVERT(DATETIME, '01/10/2014', 103) AND CONVERT(DATETIME,'31/10/2015', 103)) ORDER BY CHECKS3.RANK

Orders list based on time period

I have one table "orderdetails" table, I want Orders list from 06-01-2015 to 06-30- 15 per day below 60 orders based on time period like 00-01 and 01-02 like that
select
convert(datetime, Convert(varchar(50), OrderDate, 101)) as dateorder,
count(orderid) as ordercount
from
orderdetails
where
OrderDate between convert(datetime,Convert(varchar(50),'6/01/2015',101)) and convert(datetime,Convert(varchar(50),'06/30/2015',101))
and transactionid is not null
and DATEPART(HOUR,OrderDate) between '1' and '2'
group by
convert(datetime, Convert(varchar(50), OrderDate, 101))
having
count(orderid) < 60
But this query showing wrong list... its not displaying in count(orderid) < 60 orders its displaying overall orders, not below per day orders 60...
select * from (
select
convert(datetime, Convert(varchar(50), OrderDate, 101)) as dateorder,
count(orderid) as ordercount
from
orderdetails
where
OrderDate between convert(datetime,Convert(varchar(50),'6/01/2015',101)) and convert(datetime,Convert(varchar(50),'06/30/2015',101))
and transactionid is not null
and DATEPART(HOUR,OrderDate) between '1' and '2'
group by
convert(datetime, Convert(varchar(50), OrderDate, 101)) ) t
where ordercount < 60

SQL Server conditional query

I have a table for attendance entries looking like this :
I need a query to export the following format :
which present the Check-in and Check-out timings using British/French format (103)
I tried the following query :
SELECT
UserID,
(SELECT MIN(checktime)
FROM [FingerPrint].[dbo].[CHECKINOUT] I
WHERE CONVERT(VARCHAR(10), i.checktime, 111) = CONVERT(VARCHAR(10), p.checktime, 111)
AND i.userid = p.userid),
(SELECT MAX(checktime)
FROM [FingerPrint].[dbo].[CHECKINOUT] I
WHERE CONVERT(VARCHAR(10), i.checktime, 111) = CONVERT(VARCHAR(10), p.checktime, 111)
AND i.userid = p.userid)
FROM
[FingerPrint].[dbo].[CHECKINOUT] p
GROUP BY
p.checktime, p.UserID
Basically I need a query to select the minimum time (check-in) and maximum time (check-out) for each day using the export format above, yet when there is no value for check-in and check-out, then query should return (null) for time.
So basically you start with something like this:
SELECT UserId,
CAST(CheckTime As Date) As CheckDate,
MIN(CheckTime) As CheckIn,
MAX(CheckTime) As CheckOut
FROM [FingerPrint].[dbo].[CHECKINOUT]
GROUP BY UserId, CAST(CheckTime As Date)
For older versions of sql server (2005, 2000), you can use convert to char(10) to isolate the date part of the datetime column:
SELECT UserId,
CONVERT(char(10), CheckTime, 102) As CheckDate, /*Convert datetime format to Date*/
MIN(CheckTime) As CheckIn,
MAX(CheckTime) As CheckOut
FROM [FingerPrint].[dbo].[CHECKINOUT]
GROUP BY UserId, CONVERT(char(10), CheckTime, 102)
see fiddle here
Then you need to figure out what you want to display if the user have only one record for a day.
Also, what happens on night shifts, when a user checks in on one date, and checks out on the other date?
A better solution would be to add a bit column to specify if the record is for check in or for check out.
Update
Using case you can check if the current time is before or after whatever time of day you want to set up as the delimiter between check in and check out. In this example I've used 12 pm.
SELECT UserId,
CONVERT(char(10), CheckTime, 102) As CheckDate, /*Convert datetime format to Date*/
CASE WHEN MIN(CheckTime) <> MAX(CheckTime) THEN
MIN(CheckTime)
ELSE
CASE WHEN MIN(CheckTime) < DATEADD(Hour, 12, CONVERT(Datetime, CONVERT(char(10), CheckTime, 102), 102)) THEN
NULL
ELSE
MIN(CheckTime)
END
END As CheckIn,
CASE WHEN MIN(CheckTime) <> MAX(CheckTime) THEN
MAX(CheckTime)
ELSE
CASE WHEN MAX(CheckTime) > DATEADD(Hour, 12, CONVERT(Datetime, CONVERT(char(10), CheckTime, 102), 102)) THEN
NULL
ELSE
MAX(CheckTime)
END
END As CheckOut
FROM [CHECKINOUT]
GROUP BY UserId, CONVERT(char(10), CheckTime, 102)
Here is the relevant fiddle.

how to query two column of same table with two condition with groupby

Table :tbl_user
dateofregistration ID registrationstate
6-03-11 3 0
6-03-11 1 0
6-03-11 2 1
7-03-11 2 1
7-03-11 1 1
how can I display result like this for sql server 2008 express
date TotalID(count) Total State(0 only)
6-03-11 3 2
7-03-11 2 0
I have tried with this
SELECT CONVERT(varchar(10), dateofregistration, 103) AS Date,
(select COUNT(ID)) AS Subbase,
(Select Count(ID)from tbl_User where (registrationstate='0')) AS Totalchurn
FROM tbl_User
GROUP BY CONVERT(varchar(10), dateofregistration, 103);
but wrong result.Any help plz.
How about;
select
cast(dateofregistration as date),
count(distinct id), --or * for all
sum(
case registrationstate when '0' then 1 else 0 end
)
from tbl_user
group by cast(dateofregistration as date)
order by 1
2011-06-03 3 2
2011-07-03 2 0
SELECT CONVERT(varchar(10), dateofregistration, 103) AS Date,
COUNT(1) AS Subbase,
SUM(CASE WHEN registrationstate='0' THEN 1 ELSE 0 END) AS Totalchurn
FROM tbl_User
GROUP BY CONVERT(varchar(10), dateofregistration, 103)
ORDER BY 1
You were nearly there. You don't need a subselect for COUNT(ID) since that is handled by the GROUP BY. You group by date, and so the count will be the number of IDs within each date. I've made the count distinct, just in case you can have multiple registrations of the same ID on one day.
Your subquery was almost right - it needs to be correlated with the main query by selecting rows with the same registration date.
SELECT CONVERT(varchar(10), dateofregistration, 103) AS Date,
COUNT(DISTINCT ID) AS TotalID,
(Select Count(*) from tbl_User t2 where (registrationstate='0') AND t2.registrationdate=t1.registrationdate) AS Totalchurn
FROM tbl_User t1
GROUP BY CONVERT(varchar(10), dateofregistration, 103);

Resources