I need running VoucherNo concatenation just like running balance or total.. Concatenate the previous VoucherNo to current VoucherNo row wise just like shown in picture
Query is:
select
v.VoucherDate,v.VoucherNo,v.VoucherType,v.Narration,SUM(v.Debit) Debit , SUM(v.Credit) Credit,dbo.GetBalance(v.CompanyProfileId,v.AccountCode,v.VoucherDate ,SUM(v.Debit), SUM(v.Credit)) Balance
from AcVoucher v
where v.VoucherDate Between '2016-03-24' and '2016-03-30' and v.CompanyProfileId = 2 and v.AccountCode = '05010001'
group by v.VoucherNo,v.VoucherDate,v.VoucherType,v.Narration,v.CompanyProfileId,v.AccountCode
Schema :
GO
/****** Object: Table [dbo].[AcVoucher] Script Date: 03/30/2016 3:47:02 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[AcVoucher](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[CompanyProfileId] [int] NOT NULL,
[AccountCode] [nvarchar](50) NOT NULL,
[VoucherNo] [bigint] NOT NULL,
[VoucherType] [nvarchar](5) NOT NULL,
[VoucherDate] [datetime] NOT NULL,
[Narration] [nvarchar](500) NULL,
[Debit] [float] NOT NULL,
[Credit] [float] NOT NULL,
[TaxPercentage] [float] NULL,
[DiscountPercentage] [float] NULL,
[CreatedBy] [int] NULL,
[CreatedDate] [datetime] NULL,
CONSTRAINT [PK_ACVoucher_1] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
You can do this using basically the same logic as for string concatenation in SQL Server. The only difference is the where clause.
One key issue is the ordering for the concatenation. This is not apparent in the question, so I added a minid to the query and this is used (in reverse order) for selecting the ids to bring together:
with v as (
select v.VoucherDate, v.VoucherNo, v.VoucherType, v.Narration,
SUM(v.Debit) as Debit , SUM(v.Credit) as Credit,
dbo.GetBalance(v.CompanyProfileId, v.AccountCode, v.VoucherDate,
SUM(v.Debit), SUM(v.Credit)
) as Balance,
min(id) as minid
from AcVoucher v
where v.VoucherDate Between '2016-03-24' and '2016-03-30' and
v.CompanyProfileId = 2 and v.AccountCode = '05010001'
group by v.VoucherNo, v.VoucherDate, v.VoucherType,v.Narration, v.CompanyProfileId, v.AccountCode
)
select v.*,
stuff((select ',' + cast(v2.VoucherNo as varchar(8000))
from v v2
where v2.minid >= v.minid
for xml path ('')
), 1, 1, '') as RunningConcat
from v;
Related
I am on SQL Server 11. I have the following table that stores the boundary of all LGA in NSW
CREATE TABLE [dbo].[nsw_lga_polygon_shp](
[id] [int] IDENTITY(1,1) NOT NULL,
[geom] [geometry] NULL,
[lg_ply_pid] [nvarchar](15) NULL,
[dt_create] [date] NULL,
[dt_retire] [date] NULL,
[lga_pid] [nvarchar](15) NULL,
[nsw_lga_sh] [date] NULL,
[nsw_lga__1] [date] NULL,
[nsw_lga__2] [nvarchar](100) NULL,
[nsw_lga__3] [nvarchar](100) NULL,
[nsw_lga__4] [date] NULL,
[nsw_lga__5] [nvarchar](15) NULL,
CONSTRAINT [PK_nsw_lga_polygon_shp] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO
SET IDENTITY_INSERT [dbo].[nsw_lga_polygon_shp] ON;
The table only have 198 rows
When I try to map the result against one of my table that have 36,531 rows, I notice that it have very serious performance issue, it told 5 mins to generate 500 rows.
select
* ,
(select top 1
nsw_lga__2
from
[nsw_lga_polygon_shp]
where
Geom.Filter(geometry::STGeomFromText('point(' +
convert(varchar(100),longitude_GIS )+
' ' +
cast(latitude_GIS as varchar(100))+ ')',4283)) = 1
) LGA
from
Report_A
Is there anyway I can may it run faster? Can I index the geometry column?
Thanks in advance!
I need to have Select up to 3 company Types in SQL and use check constrain.
How to do this, or I also accept other suggestions., For the following table:
CREATE TABLE Dbo.[CompanyType](
[TypeID] [bigint] IDENTITY(1,1) NOT NULL,
[Manufacturer] [bit] NULL,
[Trading] [bit] NULL,
[BuyingOffice] [bit] NULL,
[Agent] [bit] NULL,
[Wholesaler] [bit] NULL,
[Commission] [bit] NULL,
[Association] [bit] NOT NULL,
[BusinessService] [bit] NOT NULL,
[Other] [bit] NOT NULL,
[Photo] [image] NULL,
[CreateDate] datetime
CONSTRAINT [PK_CompanyType] PRIMARY KEY CLUSTERED
(
[TypeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE dbo.[CompanyType] ADD CONSTRAINT [DF_Company_PersianTax] DEFAULT ((9)) FOR [Taxpercent]
GO
ALTER TABLE dbo.[CompanyType] ADD CONSTRAINT [DF_Company_CreateDate] DEFAULT (getdate()) FOR [CreateDate]
GO
using a check constrain.
How to use check constrain for this model??
I tried by :
In the meantime I use SP to insert. Isn't it better to check for three or more true data there? At the moment of data entry as a parameter check
--parameter validation
if(#Manufacturer+#Trading+#BuyingOffice+#Agent+#Wholesaler+#Commission+#Association+#BusinessService+#Other)<= 3
Begin
Return
End
else
insert statement (...)
Using trigger like following query! check inserted, sum of column <= 3 rolback
CREATE TRIGGER usp_checksum3
ON dbo.companytype
AFTER insert
AS
BEGIN
SET NOCOUNT ON;
if (Select [Manufacturer]+[Trading]+[BuyingOffice]+[Agent]+[Wholesaler]+[Commission]+[Association]+[BusinessService]+[Other]
From inserted) <= 3
Return
END
Thanks for your tips
Consider using the following check constraint:
CREATE TABLE Dbo.[CompanyType](
[TypeID] [bigint] IDENTITY(1,1) NOT NULL,
[Manufacturer] [bit] NULL,
[Trading] [bit] NULL,
[BuyingOffice] [bit] NULL,
[Agent] [bit] NULL,
[Wholesaler] [bit] NULL,
[Commission] [bit] NULL,
[Association] [bit] NOT NULL,
[BusinessService] [bit] NOT NULL,
[Other] [bit] NOT NULL,
[Photo] [image] NULL,
[CreateDate] datetime
CONSTRAINT [PK_CompanyType] PRIMARY KEY CLUSTERED ([TypeID] ASC)
WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON,
OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY],
CONSTRAINT [PK_Company_Types] CHECK (
CAST([Manufacturer] AS INT)
+ CAST([Trading] AS INT)
+ CAST([BuyingOffice] AS INT)
+ CAST([Agent] AS INT)
+ CAST([Wholesaler] AS INT)
+ CAST([Commission] AS INT)
+ CAST([Association] AS INT)
+ CAST([BusinessService] AS INT)
+ CAST([Other] AS INT)
<= 3)
You don't need to implement additional logic in your stored procedure. The check constraint guarantees integrity, and apply equally to inserts performed from the SP or outside.
If you want to modify the existing table:
ALTER TABLE Dbo.[CompanyType]
ADD CONSTRAINT [Chk_CompanyType] CHECK (
CAST([Manufacturer] AS INT)
+ CAST([Trading] AS INT)
+ CAST([BuyingOffice] AS INT)
+ CAST([Agent] AS INT)
+ CAST([Wholesaler] AS INT)
+ CAST([Commission] AS INT)
+ CAST([Association] AS INT)
+ CAST([BusinessService] AS INT)
+ CAST([Other] AS INT)
<= 3)
I have two tables as below:
1) UserFavouriteCurrencies
CREATE TABLE [dbo].[UserFavouriteCurrencies](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[UserId] [int] NULL,
[CurrencyId] [int] NULL,
[EntryDate] [datetime] NULL,
CONSTRAINT [PK_UserFavouriteCurrencies] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Above table is holding data of user favorite companies
2) CurrencyRates
CREATE TABLE [dbo].[CurrencyRates](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[CurrencyId] [int] NULL,
[Price] [float] NULL,
[Open_24h] [float] NULL,
[Volume_24h] [float] NULL,
[Low_24h] [float] NULL,
[High_24h] [float] NULL,
[Volume_30d] [float] NULL,
[BestBid] [float] NULL,
[BestAsk] [float] NULL,
[TradeId] [bigint] NULL,
[PriceDate] [datetime] NULL,
[PriceDateTimestamp] [bigint] NULL,
[OpenInterest] [float] NULL,
CONSTRAINT [PK_CoinbaseTickerRatesMaster] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Above table holds rates details of currencies.
Call : EXEC sp_Getdata 1(Here 1 in UserId of UserFavouriteCurrencies table)
I need all records for particular currencies last latest records in one query as below
DECLARE #Today DATETIME = GETDATE(), #PrevDate DATETIME = GETDATE()<br>
SELECT TOP 1 Price, PriceDate, Volume_24h, PriceDateTimestamp
FROM CurrencyRates
WHERE CurrencyId = #CurrencyId AND PriceDate <= #Today
ORDER BY PriceDateTimestamp DESC
Above query is only select data for one particular currency but I need the data related to user which added on UserFavouriteCurrencies table.
Please help me to write store procedure for this query
Thanks in advance.
For each currency in UserFavouriteCurrencies Table, consider the query below
SELECT
uc.Id -- This is the userId
,cr.Price
,cr.PriceDate,
,cr.Volume_24h
,cr.PriceDateTimestamp
FROM
UserFavouriteCurrencies AS uc
INNER JOIN CurrencyRates AS cr -- See Hints : 1
ON cr.CurrencyId = uc.CurrencyId
WHERE
PriceDate <= GETDATE()
AND
uc.Id = #Id
-- You can add other Predicates Here...
Hints:
Consider using LEFT OUTER JOIN if user's currency may not exist in CurrencyRates
!This will however introduce NULLs which you must handle
INSERT INTO dbo.SaleNew(ENQ_AID,DOCKET_NO,SALE_TYPE,VEHICLE_MODEL,SALE_DATE,BOOKING_DATE,DELIVERY_DATE,
DEALER_NAME,ENQ_GEN_BY,EXEC_NAME,USER_CR,DATE_CR) SELECT '6','2','0','TEST','2016-05-01','2016-05-10','2016-05-15',
'ABC','S I','V B','1',SWITCHOFFSET(SYSDATETIMEOFFSET(), '+05:30')
What could be wrong with this query?
Also tried:
INSERT INTO dbo.SaleNew(ENQ_AID,DOCKET_NO,SALE_TYPE,VEHICLE_MODEL,SALE_DATE,BOOKING_DATE,DELIVERY_DATE,
DEALER_NAME,ENQ_GEN_BY,EXEC_NAME,USER_CR,DATE_CR) SELECT '6','2','0','TEST',CONVERT(DATE,'01/05/2016',103),CONVERT(DATE,'10/05/2016',103),
CONVERT(DATE,'15/05/2016',103),'ABC','S I','V B','1',SWITCHOFFSET(SYSDATETIMEOFFSET(), '+05:30')
This is the create table query:
CREATE TABLE [dbo].[SaleNew](
[SALE_ID] [int] IDENTITY(1,1) NOT NULL,
[ENQ_AID] [bigint] NOT NULL,
[DOCKET_NO] [varchar](50) NOT NULL,
[VEHICLE_MODEL] [varchar](100) NOT NULL,
[SALE_DATE] [date] NULL,
[BOOKING_DATE] [date] NULL,
[DELIVERY_DATE] [date] NULL,
[DEALER_NAME] [date] NULL,
[ENQ_GEN_BY] [varchar](100) NULL,
[EXEC_NAME] [varchar](100) NULL,
[USER_CR] [int] NULL,
[DATE_CR] [date] NULL,
[USER_UP] [int] NULL,
[DATE_UP] [date] NULL,
[SALE_TYPE] [int] NOT NULL,CONSTRAINT [PK_SaleNew] PRIMARY KEY CLUSTERED (
[SALE_ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON ) ON [PRIMARY]
What could be the reason?
DEALER_NAME type is defined as DATE but you want to INSERT a VARCHAR type value ABC in it.
Execute following query in order to edit the mentioned column type, then Execute your INSERT query.
ALTER TABLE [dbo].[SaleNew]
ALTER COLUMN [DEALER_NAME] VARCHAR(50) NULL
I have a very simple SQL query:
select o.Visit_ID
from Datamart.dbo.ww_Orders o
inner join Datamart.dbo.ww_Order_Details on o.Visit_ID = ww_Order_Details.Visit_ID
where o.runstamp = '20160422'
this query takes < 0 seconds to return 11173 rows
When I add the GROUP BY statement:
select o.Visit_ID
from Datamart.dbo.ww_Orders o
inner join Datamart.dbo.ww_Order_Details on o.Visit_ID = ww_Order_Details.Visit_ID
where o.runstamp = '20160422'
group by o.Visit_ID
the server takes 6min 30 sec to retrieve the 3047 rows.
I would expect the GROUP BY query to take not that much longer than the original. How do I go about finding what the issues are? thanks
here are the table definitions:
Orders:
CREATE TABLE [dbo].[ww_Orders](
[Visit_ID] [int] NOT NULL,
[Member_ID] [int] NOT NULL,
[Membership_no] [varchar](20) NULL,
[Member_Card_Num_Orig] [varchar](16) NULL,
[SCV_ID] [int] NULL,
[Meeting_No] [int] NULL,
[Location_Name] [varchar](128) NULL,
[Leader_No] [int] NULL,
[CashAmt] [decimal](18, 2) NULL,
[EFTAmt] [decimal](18, 2) NULL,
[VouchAmt] [decimal](18, 2) NULL,
[Meet_Date] [datetime] NULL,
[runstamp] [varchar](50) NULL,
CONSTRAINT [PK_dbo.ww_Orders] PRIMARY KEY CLUSTERED
(
[Visit_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
Order Details:
CREATE TABLE [dbo].[ww_Order_Details](
[ord_det_pk] [int] IDENTITY(1,1) NOT NULL,
[Visit_ID] [int] NOT NULL,
[Item_Code] [nvarchar](50) NULL,
[Item_Name] [nvarchar](50) NULL,
[Qty] [int] NULL,
[Amt] [decimal](18, 2) NULL,
[Category_Code] [nvarchar](20) NULL,
CONSTRAINT [PK_ww_Order_Details] PRIMARY KEY CLUSTERED
(
[ord_det_pk] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ww_Order_Details] WITH CHECK ADD CONSTRAINT [FK_ww_Order_Details_ww_Orders] FOREIGN KEY([Visit_ID])
REFERENCES [dbo].[ww_Orders] ([Visit_ID])
GO
ALTER TABLE [dbo].[ww_Order_Details] CHECK CONSTRAINT [FK_ww_Order_Details_ww_Orders]
GO
I'd add an index onto ww_Order_Details Visit_ID, probably make it the clustered index and drop the index on ord_det_pk. Also it might make more sense as an exists?
select o.Visit_ID
from Datamart.dbo.ww_Orders o
where exists (select 0 from Datamart.dbo.ww_Order_Details where o.Visit_ID = ww_Order_Details.Visit_ID)
and o.runstamp = '20160422'
I usually try to use a common table expression in cases like these, when a part of the query is really fast but an addition of a simple operation makes it really slow, usually it helps.
Try:
WITH CTE AS (
select o.Visit_ID
from Datamart.dbo.ww_Orders o
inner join Datamart.dbo.ww_Order_Details od on o.Visit_ID = od.Visit_ID
where o.runstamp = '20160422'
)
SELECT Visit_ID FROM CTE
group by Visit_ID
If this helps you can try to compare execution plans for your original query and this version to see whats going on